In this question here on S.O, the accepted answer suggests to use both anonymous function and factory pattern for dealing with PDO connection. I believe the anonymous function is used in case a connection to a different database needs to be established, a different function will be defined for that. In that case, will it be alright to move the anonymous function to the factory class itself for just a single database?
This is what I had in mind
class StructureFactory
{
protected $provider = null;
protected $connection = null;
public function __construct( )
{
$this->provider = function() {
$instance = new PDO('mysql:......;charset=utf8', 'username', 'password');
$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $instance;
};
}
public function create( $name )
{
if ( $this->connection === null )
{
$this->connection = call_user_func( $this->provider );
}
return new $name( $this->connection );
}
}
Also, even with this approach why not just passing the PDO parameters to the constructor achieve what the original answer was trying to achieve, i.e to establish different connections?
Something like:
class StructureFactory
{
protected $provider = null;
protected $connection = null;
public function __construct( $PDO_Params )
{
$this->provider = function() {
$instance = new PDO($PDO_Params["dsn"], $PDO_Params["username"], $PDO_Params["password"]);
$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $instance;
};
}
public function create( $name)
{
if ( $this->connection === null )
{
$this->connection = call_user_func( $this->provider );
}
return new $name( $this->connection );
}
}