Using Interfaces for Repositories in PHP
I’m working on a restructuring/re-design of the web site VGMusic. This is my first attempt at applying such delightful techniques such as the Repository Pattern and Dependency Injection in PHP, and that language does not make this easy. Support for object-oriented techniques is not the best, and the biggest obstacle is the fact that PHP is weakly typed. This makes it really difficult to do things like program against an interface. If I wrote the line:
<?php
$fooRepository = new FooRepository();
?>
Then I’m actually instantiating an instance of the concrete implementation FooRepository(). What I would like to do, however, Is use the interface IFooRepository instead. What I decided to do is to take a page out of the MVC Pattern and use controllers. A controller can have a private instance of a repository.
<?php
class FooController
{
private $_fooRepository;
function __construct(IFooRepository $fooRepository)
{
$this->_fooRepository = $fooRepository;
}
public function GetFoo($id)
{
return $this->_fooRepository->GetFoo($id);
}
}
?>
<?php
class FooController
{
private $_fooRepository;
function __construct(IFooRepository $fooRepository = null)
{
if ($fooRepository = null)
{
$fooRepository = new FooRepository();
}
$this->_fooRepository = $fooRepository;
}
}
?>
