Search code examples
phpdesign-patternssingletonpdofactory-pattern

Explain this singleton factory pattern


class ConnectionFactory
{
    private static $factory;
    public static function getFactory()
    {
        if (!self::$factory)
            self::$factory = new ConnectionFactory(...);
        return self::$factory;
    }

    private $db;

    public function getConnection() {
        if (!$db)
            $db = new PDO(...);
        return $db;
    }
}

function getSomething()
{
    $conn = ConnectionFactory::getFactory()->getConnection();
    .
    .
    .
}

Source

There are a couple of things that i dont get

  1. Am i right when i say "staic property of a class can be accessed without initiating the class"
  2. what does !db do
  3. How is this happening ConnectionFactory::getFactory()->getConnection();
  4. Could somebody explain getFactory method

Solution

    1. you are right here.
    2. ! is a NOT. Which means here that if $db is false then initialise it. Since its in a static method it will stay initialised and next time the existiong $db will be returned since this second time !$db == false.
    3. like for $db it is checking if an instance of $factory exists, if not create one and returne it, otherwise return the existing one.

    4.

    public static function getFactory()
    {
         if (!self::$factory) // is self::$factory initialised?
                self::$factory = new ConnectionFactory(...); //initialise it
         return self::$factory; //return self::$factory
    }
    

    Also here $factory seems to be a variable that is set somewhere eles. Presumably it could contain a couple of different class names. Does not change anything to the way the function works. Its a singleton pattern

    Adding a interesting link about this pattern wikipedia