How to call Service in controller in Service layer with repository pattern

Viewed 62

I'm learning about Service layer with repository pattern in Laravel. So, I have a question:

I have two services: ProductService and PostService. Both services have getAll function:

class ProductService 
{
    public function getAll()
    {
        return $this->productRepository->getAll();
    }
}

class PostService 
{
    public function getAll()
    {
        return $this->postRepository->getAll();
    }
}

In HomeController, action index, I wanna show all posts and products. How should I code ?

Option 1. Call two services, then call getAll:

class HomeController
{
    public function index(){
        $products = $this->productService->getAll();
        $posts = $this->postService->getAll();

        return view('index', compact('posts', 'products'));
    }
}

Option 2. Declare HomeService, then call:

class HomeService 
{
    public function index()
    {
        return [
            'products'  => $this->productRepository->getAll(),
            'posts'     => $this->postRepository->getAll()
        ];
    }
}

----------

class HomeController
{
    public function index(){
        $data = $this->homeService->index();
        return view('index', $data);
    }
}

Pls help me! Thank you!

0 Answers
Related