I'm using a simple project to help me understand and implement MVC with DI in preparation for unit testing. The site simply will display a different table of data based on the page requested. The difficulty comes in the data could come from different data sources (mysql or oracle for example), so I'm trying to implement DI to reduce the code needed to switch between the two. My problems are these:
1) Where to instantiate the data source (could be mysql, oracle or even a plain old array) and get it to the object(s) that require it (is DI even the best pattern for this)?
2) Where in the structure of things to put the data query specific to its source? Per my example below, I have a class Foo that queries a MySQL database for data but if I move to an Oracle database later it all has to be rewritten for a different syntax. Do I just create two versions FooMysql and FooOracle and tell something somewhere which to use?
Here is some basic, incomplete code demonstrating the concept as I'm seeing it. Hopefully you understand where I'm going with this and can point me in the right direction. I am not looking for an already built framework.
$c = new Controller('foo');
print_r($c->getContent());
class Controller
{
private $view = null;
public function __construct($viewName)
{
$this->view = new $viewName($dbc); // where to get and pass dbc based on view
}
}
interface ViewInterface
{
public function getContent();
}
class FooView
{
private $foo = null;
public function __construct(DatabaseConnection &$dbc)
{
$this->foo = new Foo($dbc);
}
public function getContent()
{
return $this->foo->getAll();
}
}
class BarView
{
private $bar = null;
public function __construct(DatabaseConnection &$dbc)
{
$this->bar = new Bar($dbc);
}
public function getContent()
{
return $this->bar->getAll();
}
}
interface StorageInterface
{
public function getAll();
}
class Foo implements StorageInterface
{
private $dbc = null;
public function __construct(DatabaseConnection &$dbc)
{
$this->dbc = $dbc;
}
public function getAll()
{
// mysql code to get all foos
}
}
class Bar implements StorageInterface
{
private $dbc = null;
public function __construct(DatabaseConnection &$dbc)
{
$this->dbc = $dbc;
}
public function getAll()
{
// oracle code to get all bars
}
}