0

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 );
    }

}
Community
  • 1
  • 1
  • Just to clarify. That anonymous function is used to make a connection on demand. It connects once when it's called the first time – Your Common Sense May 11 '17 at 05:55
  • @YourCommonSense I did understand that part, but that anonymous function can be a part of the constructor too, right? –  May 11 '17 at 08:10
  • @feetnappy constructor should not contain logic, because it make the class impossible to unit-test. – tereško May 12 '17 at 14:12

1 Answers1

0

No. Because that way you loos any benefits from dependency injection.

The modification, that you could to is: inject an initialized PDO instance directly in the factory, instead of using this lazy-loading approach. Kinda like in this answer.

I would also recommend watching this lecture.

Community
  • 1
  • 1
tereško
  • 56,151
  • 24
  • 92
  • 147