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? With this approach just passing the PDO parameters to the constructor will achieve the same as the original answer.
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 );
}
}