In my recent laravel 5 project, I use to prepare my logic as a repository method. So here is my current directory structure. For example, we have a "Car".
So first, I just create a directory that calls its libs in the app directory and load it into composer.json
"autoload": { "classmap": [ "database", "app/libs" //this is the new changes (remove this comment) ] }
after that I create a subfolder calling her Car . In the "Car" folder, create two files "CarEloquent.php" for the CarInterface.php implementation and CarInterface.php as the interface.
Carinterface
namespace App\libs\Car; interface CarInterface { public function getAll(); public function create(array $data); public function delete($id); public function getByID($id); public function update($id,array $data); }
Careloquent
namespace App\lib\Car; use App\lib\Car\CarInterface; use App\Car;
Then create an Auto Seller to bind the ioc controller. You can also use the php artisan command from laravel to create a car service. php artisan make:provider CarServiceProvider
ServiceProvider
namespace App\Providers; use Illuminate\Support\ServiceProvider; class CarServiceProvider extends ServiceProvider { public function register() { $this->app->bind('App\lib\Car\CarInterface', 'App\lib\Car\CarEloquent'); } }
And the last step is to add these service providers to the config/app.php providers array.
'providers' => [ 'App\Providers\CatServiceProvider', ]
And finally, we are ready to use our repository method in our controller.
Controller example
namespace App\Http\Controllers; use App\lib\Car\CarInterface as Car; class CarController extends Controller { protected $carObject; public function __construct(Car $c) { $this->carObject = $c; } public function getIndex(){ $cars = $this->carObject->getAll(); return view('cars.index')->with('cars',$cars); } }
The main goal here is to achieve the call repository method for the controller, however you need to use them as per your requirement.
Update
CarEloqent mainly helps us improve the database implementation, for example, in the future, if you want to implement the same functions for a different database as redis , you simply add another CarRedis class and change the path to the implementation file from the server provider.
Update 1: Good Resource
http://programmingarehard.com/2014/03/12/what-to-return-from-repositories.html
[book] From apprentice to artisan Taylor Otwell
A very good explanation of the repository method and the principle of software development, commonly called separation of problems. You must read this book.
If you still have confusion for this behavior, let me know, and nonetheless, I will follow up on this issue to update this answer if I find some things to change or update, or on demand.