Last active
December 11, 2015 20:08
-
-
Save JeffreyWay/4652702 to your computer and use it in GitHub Desktop.
Testable Laravel.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
}); |
Yeah, the IoC container will resolve default arguments now, so shouldn't get any exceptions here.
The idea of a Dog being an extension of Eloquent makes little sense. A dog is not a type of database abstraction.
Great to hear. Thanks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@eoconnell - You should update your repo to the latest one. do composer update
That issue is already solved here - laravel/framework#80