Skip to content

Instantly share code, notes, and snippets.

@JeffreyWay
Last active December 11, 2015 20:08
Show Gist options
  • Save JeffreyWay/4652702 to your computer and use it in GitHub Desktop.
Save JeffreyWay/4652702 to your computer and use it in GitHub Desktop.
Testable Laravel.
<?php
class DogsController extends BaseController {
protected $db;
// Let the db-layer be injected. Don't worry...
// Laravel will automatically inject the dependencies for you.
function __construct(DogInterface $db) {
$this->db = $db;
}
public function index()
{
var_dump($this->db->getAll());
}
}
<?php
// When you need an instance of DogInterface,
// use the Eloquent implementation. Easy to switch out.
App::bind('DogInterface', 'EloquentDog');
// Let's define a contract for what any implementation
// of DogInterface should offer.
interface DogInterface {
public function getAll();
}
// Here's our first implementation: an Eloquent one.
class EloquentDog extends Eloquent implements DogInterface {
public $table = 'dogs';
public function getAll()
{
return static::all();
}
}
// And our second implementation, perhaps for a simple Array "DB"
class ArrayDog implements DogInterface {
public function getAll()
{
return ['sparky', 'trash', 'ham'];
}
}
route::get('/', function() {
// Laravel is smart enough to inject the necessary
// dependencies for, using reflection.
$dog = App::make('DogInterface');
// Try changing line 5 to the second implementation, ArrayDog
// Instance switch!
$dog->getAll();
});
@johnnncodes
Copy link

@eoconnell - You should update your repo to the latest one. do composer update

That issue is already solved here - laravel/framework#80

@taylorotwell
Copy link

Yeah, the IoC container will resolve default arguments now, so shouldn't get any exceptions here.

@trq
Copy link

trq commented Jan 28, 2013

The idea of a Dog being an extension of Eloquent makes little sense. A dog is not a type of database abstraction.

@eoconnell
Copy link

Great to hear. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment