Creating the Singleton design pattern in PHP5

前端 未结 21 2074
猫巷女王i
猫巷女王i 2020-11-22 04:21

How would one create a Singleton class using PHP5 classes?

21条回答
  •  日久生厌
    2020-11-22 05:09

    You don't really need to use Singleton pattern because it's considered to be an antipattern. Basically there is a lot of reasons to not to implement this pattern at all. Read this to start with: Best practice on PHP singleton classes.

    If after all you still think you need to use Singleton pattern then we could write a class that will allow us to get Singleton functionality by extending our SingletonClassVendor abstract class.

    This is what I came with to solve this problem.

    Use example:

    /**
     * EXAMPLE
     */
    
    /**
     *  @example 1 - Database class by extending SingletonClassVendor abstract class becomes fully functional singleton
     *  __constructor must be set to protected becaouse: 
     *   1 to allow instansiation from parent class 
     *   2 to prevent direct instanciation of object with "new" keword.
     *   3 to meet requierments of SingletonClassVendor abstract class
     */
    class Database extends SingletonClassVendor
    {
        public $type = "SomeClass";
        protected function __construct(){
            echo "DDDDDDDDD". PHP_EOL; // remove this line after testing
        }
    }
    
    
    /**
     *  @example 2 - Config ...
     */
    class Config extends SingletonClassVendor
    {
        public $name = "Config";
        protected function __construct(){
            echo "CCCCCCCCCC" . PHP_EOL; // remove this line after testing
        }
    }
    

    Just to prove that it works as expected:

    /**
     *  TESTING
     */
    $bd1 = Database::getInstance(); // new
    $bd2 = Database::getInstance(); // old
    $bd3 = Config::getInstance(); // new
    $bd4 = Config::getInstance(); // old
    $bd5 = Config::getInstance(); // old
    $bd6 = Database::getInstance(); // old
    $bd7 = Database::getInstance(); // old
    $bd8 = Config::getInstance(); // old
    
    echo PHP_EOL."COMPARE ALL DATABASE INSTANCES".PHP_EOL;
    var_dump($bd1);
    echo '$bd1 === $bd2' . ($bd1 === $bd2)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
    echo '$bd2 === $bd6' . ($bd2 === $bd6)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
    echo '$bd6 === $bd7' . ($bd6 === $bd7)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
    
    echo PHP_EOL;
    
    echo PHP_EOL."COMPARE ALL CONFIG INSTANCES". PHP_EOL;
    var_dump($bd3);
    echo '$bd3 === $bd4' . ($bd3 === $bd4)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
    echo '$bd4 === $bd5' . ($bd4 === $bd5)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
    echo '$bd5 === $bd8' . ($bd5 === $bd8)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
    

提交回复
热议问题