Laravel : Repositories the right way
If you want to make your application testable you should really use Repositories in order to perform unit tests without touching the database.
In my case I was programming a Fantasy Football game and I will stick with the Team model.
The Team model has some attributes eg : Name, Colors and Formation which was an enumerator of various Formations.
On your app if you accessed the model directly on your Controller than testing the controller and trying to bypass a database call would be impossible and database calls are expensive. Imagine if you had a gulp task on elixir to perform unit tests on ‘watch’, every time you saved something that would do a call to database eg :
<?php namespace App\Http\Controllers;
use Offside\Models\Team;
class HomeController extends Controller {
protected $team;
public function __construct(Team $team){
$this->team = $team;
}
/**
* Show the application dashboard to the user.
*
* @return Response
*/
public function getPlayers()
{
return $this->team->players;
}
}
Everytime you hit getPlayers() you would make a call to database.
To avoid that you should create a repository and inject it on your controller by passing it to the Controller constructor.
You need to create an interface so it can be mocked eg :
<?php namespace Offside\Repo;
interface TeamRepositoryInterface {
public function getPlayers();
}
//And then you should create a concrete implementation of that interface eg :
<?php namespace Offside\Repo;
use Offside\Models\Team;
use Offside\Random;
class TeamRepository implements TeamRepositoryInterface{
protected $team = null;
public function __construct(Team $team){
$this->team = $team;
}
Link:
This post is submitted by our members. Submit a new post.
Tags: Tutorials Laravel 5 Laravel 5.1