zendaemon/service-layer

Service layer generator for laravel applications

2.0.0 2021-02-23 15:13 UTC

This package is auto-updated.

Last update: 2024-04-23 22:27:35 UTC


README

License Build Status Scrutinizer Code Quality Latest Stable Version Total Downloads StyleCI

This Laravel package provides support for simple service layer. Service class the best place for your business logic.

Installation

Require this package with composer.

composer require zendaemon/service-layer

If you don't use auto-discovery, add the ServiceProvider to the providers array in config/app.php

Zendaemon\Services\ServiceLayerGeneratorServiceProvider::class,

After installing ServiceLayer, publish its assets using the services:install Artisan command:

php artisan services:install

Usage

Simple service

Using the make:service Artisan command, you can quickly create such a base service:

php artisan make:service SomeService

Static service

Or you can create static service for simple tasks:

php artisan make:service SomeService --static

You can now add SomeService in your controller through DI:

final class SomeController extends Controller
{
    /** @var SomeService $service */
    private $service;

    public function __construct(SomeService $service)
    {
        $this->service = $service;
    }

    public function index(): ?ResourceCollection
    {
        return SomeCollection::collection($this->service->someListMethod());
    }

    public function store(StoreSomeRequest $request): ?JsonResource
    {
        return SomeResource::make($this->service->someCreationMethod($request));
    }

    public function update(UpdateSomeRequest $request, SomeModel $model): ?JsonResource
    {
        return SomeResource::make($this->service->someUpdatingMethod($request, $model));
    }

    public function destroy(SomeModel $model): JsonResponse
    {
        if (! $this->service->someDestroyMethod($model)) {
            return response()->json([
                'message' => 'Some error.',
            ], Response::HTTP_INTERNAL_SERVER_ERROR);        
        }

        return response()->json(['success' => Response::HTTP_OK]);
    }
}

Service class binding

You can bind your services in Providers/ServiceLayerServiceProvider class like so.

namespace App\Providers;

use App\Services\LocationService;
use Illuminate\Support\ServiceProvider;

class ServiceLayerServiceProvider extends ServiceProvider
{
    /**
         * Register any application services.
         *
         * @return void
         */
        public function register()
        {
            $this->app->singleton(LocationService::class, function () {
                return new LocationService;
            });
        }
}