I am trying to learn the repository pattern, and seem to have got myself a tad confused with how I can use this repository pattern when eager loading relationships and keep db logic out of my controller.
A quick overview of my repository / application structure.
app/
Acme/
Repositories/
RepositoryServiceProvider.php
Product/
EloquentProduct.php
ProductInterface.php
Category/
EloquentCategory.php
CategoryInterface.php
Example ProductInterface.php
<?php namespace GD\Repositories\Product;
interface ProductInterface
{
public function all();
public function find($id);
public function findBySlug($slug);
}
Example CategoryInterface.php
<?php namespace GD\Repositories\Category;
interface CategoryInterface
{
public function all();
public function find($id);
public function findBySlug($slug);
}
Ok, so the easy part is using DI to inject model dependencies into the controller.
listing all categories with associated products is more difficult as I am no longer working with an eloquent model. I am working with an interface which has not exposed all the eloquent methods.
This won't work without me implementing a with method within my EloquentCategory class...
public function show($slug)
{
return Response::json($this->category->findBySlug($slug)->with('products'), 200);
}
Should I create a separate service class to glue the two repositories together? e.g. allowing the following
public function __construct(ShopService $shop)
{
$this->shop = $shop;
}
public function show($slug)
{
return Response::json( $this->shop->getProductsInCategory($slug), 200 );
}
Or alternatively, should I be implementing the with method in my Category Repository?
public function with($relation)
{
return Category::with($relation);
}
Finally, is my understanding of the usage of the Repository Pattern Correct?