I was wondering how most developers use this two Laravel tools.
In Laravel, you can handle business logic with Services, or with Jobs (let's talk only about not-queueable jobs, only those ones that run in the same process).
For example, an user wants to create an entity, let's 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 something 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.
Request
object to the service. The request is an object you receive when the user performs an HTTP request. If you directly pass it to the service, it means you cannot use the same service within a console command or a (queued) job, because you miss the request. In my opinion, the controller should transform the request into a model or DTO (data transfer object) and call the service function with these as parameter. – Addressograph