Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Middleware class be used as a Service layer?

In most of Java cases there exist two classes: one responsible for apply my business rules - Service layer - and another one responsible for interacting with my database - Dao/Repository layer. However, in PHP cases I just have one class that represents model Layer. My question is, assuming Laravel Framework, should I put my business rules inside a unique model class or there is another approach similar with JSF for instance? Can I use a Middleware class as a Service layer?

like image 454
user3700308 Avatar asked Jan 25 '26 17:01

user3700308


1 Answers

To be honest you can use Service/Repo Layers in PHP as well.

So what happens is

  1. Controller passes the inputs to the service and service decides what action is to be done.
  2. The Service Layer then calls the repo for receiving entries from database wherever necessary and perform all the business logic.
  3. The Repo calls the model and data from the model is returned.
  4. The Model only keeps Model specific data (like relations, appended attributes, casts array etc etc...)

To follow this approach, something like this can be done.

Controller

use App\Services\PostService;

class PostController
{
  public function __construct()
  {
    $this->postService = new PostService;
  }

  public function show($id)
  {
    $viewData = $this->postService->getPostData($id);

    return view('posts.show', $viewData);
  }
}

Service Layer

use App\Repositories\PostRepository;
use App\Repositories\CommentRepository;

class PostService
{
  public function __construct()
  {
    $this->postRepo = new PostRepository;

    $this->commentRepo = new CommentRepository;
  }

  public function getPostData($id)
  {
    $post = $this->postRepo->get($id);

    $recentComments = $this->commentsRepo->getRecentComments();

    return collect(compact('post', 'recentComments'));
  }
}

Repository Layer

use App\Models\Post;

public function PostRepository
{
  public function get()
  {
    return Post::findOrFail($id);
  }
}

Also, for your last question, I'd like to say, Middlewares are meant to be used as a per-requisite only. In other words, lets say you want to ensure a user is logged in to view that particular route, then you'll apply the auth middleware and protect your routes from other not-logged in users... According to me, using Service Layer as Middleware isn't really required. You can obviously call a service layer in a Middleware by $this->myService = new Service but making it as a middleware doesn't really sound a good practice.

Hope I answered your question well enough :)

like image 105
prateekkathal Avatar answered Jan 28 '26 07:01

prateekkathal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!