Service classes are written to encapsulate codes and business logic separately from controllers. These classes should work for a service or operation. Unlike other classes, service classes do not inherit from other classes or controllers. Instead, the functions get called by object.
Convention:App\Services
namespace.PostService
, CommentService
etc.<?php
namespace App\Services;
class PostService
{
public function store($data)
{
// Any logical block
$post = Post::create($data);
if ($post) {
return $post;
} else {
throw new \Exception('Not stored. Something is wrong!');
}
}
}
Using the Functionality
Now from any controller, you can call the function store
by an instance of PostService
.
public function storePost(Request $request, PostService $service)
{
// Some validation
// Some data formatting and making an associative array.
try {
$service->store($insertionArray);
} catch (\Exception $exception) {
return response()->json(['error' => $exception->getMessage()], 422);
}
return response()->json([....], 200);
}
As you can see, in my service function I received data and stored it in the DB table, and if any issue happens I return an exception. The service should return the result to the controller, not to the view.
This is just a simple use case, you can go deeper with service classes. Definitely follow the More Documentation on Medium for details.