vendredi 19 octobre 2018

Laravel patterns - Usage of jobs vs services

I was wondering how most developers use this two Laravel tools.

In Laravel, you can handle business logic with Services, or with Jobs (lets talk only about not-queueable jobs, only those ones that run in the same process).

For example: an user wants to create an entity, lets say a Book, you can handle the entity creation with a service or dispatching a job.

Using a job it would be something like this:

class PostBook extends Job
{
    ...
    public function handle(Book $bookEntity)
    {
        // Business logic here.
    }
    ...
}

class BooksController extends Controller
{
    public function store(Request $request)
    {
        ...
        dispatch(new PostBook($request->all()));
        ...
    }
}

Using a service, it would be somthing like this:

class BookService
{
    public function store(Request $request)
    {
        // Business logic here.
    }
}

class BooksController extends Controller
{
    public function store(Request $request)
    {
        ...
        // I could inject the service instead.
        $bookService = $this->app()->make(App\Services\BookService::class);
        $bookService->store($request);
        ...
    }
}

The question is, how do you mostly choose to use one way or the other one? And why?

Surely there are two "schools" in this matter, but I would want to understand pros & cons of each one.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire