Since you have tagged this as mvc, I will assume that your DAOs already exist within the model layer. As i understand it. the DAOs are responsible for for same task as Data Mappers, and provide the information from storage (which might or might not be SQL database) to your Domain Objects within the Model Layer.
The best way to deal with this issue would be to have factory, which create the data access objects within your model layer. This would have several advantages:
- decoupling from the class names of different DAOs
- ability to know when first DAO is initialized
- sharing single DB connection between all DAO instances
This is how I would implement something like it:
class DaoFactory
{
protected $connection = null;
protected $provider = null;
public function __construct( $provider )
{
$this->provider = $provider;
}
public function create( $name )
{
if ( $connection === null )
{
$connection = call_user_func( $this->provider );
}
$instance = new $name;
$instance->setConnection( $connection );
return $instance
}
}
And the usage would look something like this:
$connectionProvider = function()
{
$instance = new \PDO('mysql:host=localhost;dbname=testdb;charset=utf8',
'username', 'password');
$instance->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$instance->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
return $instance;
};
$daoFactory = new DaoFactory( $connectionProvider );
Then you pass the $daoFactory
variable to whichever object will require to create DAO. This way, if need arises, you can easily replace the factory (as long as it implements same create()
method footprint), with something completely different. And your domain business logic is in no way impacted by such a change.
The objects which use this factory became completely unaware that there even exists a database connection, and that DAOs need it to function. And you can even end up with situations, when you don't even need to establish a connection to database.
Rant
Since you have data access objects on your codebase, it would indicate that you are trying to use OOP. Or at least something similar. But the static classes/functions/variables are not part of OOP paradigm. If you have a class with static-only methods and few static variables, what you have actually made are just simple php function with global variables, wrapped in a namespace, which just happens to look like class.
PHP community tends to call this COP (class oriented programming) as a joke, but essentially it is procedural code.