Creating the Singleton design pattern in PHP5

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

How would one create a Singleton class using PHP5 classes?

21条回答
  •  孤独总比滥情好
    2020-11-22 04:56

    Supports Multiple Objects with 1 line per class:

    This method will enforce singletons on any class you wish, al you have to do is add 1 method to the class you wish to make a singleton and this will do it for you.

    This also stores objects in a "SingleTonBase" class so you can debug all your objects that you have used in your system by recursing the SingleTonBase objects.


    Create a file called SingletonBase.php and include it in root of your script!

    The code is

    abstract class SingletonBase
    {
        private static $storage = array();
    
        public static function Singleton($class)
        {
            if(in_array($class,self::$storage))
            {
                return self::$storage[$class];
            }
            return self::$storage[$class] = new $class();
        }
        public static function storage()
        {
           return self::$storage;
        }
    }
    

    Then for any class you want to make a singleton just add this small single method.

    public static function Singleton()
    {
        return SingletonBase::Singleton(get_class());
    }
    

    Here is a small example:

    include 'libraries/SingletonBase.resource.php';
    
    class Database
    {
        //Add that singleton function.
        public static function Singleton()
        {
            return SingletonBase::Singleton(get_class());
        }
    
        public function run()
        {
            echo 'running...';
        }
    }
    
    $Database = Database::Singleton();
    
    $Database->run();
    

    And you can just add this singleton function in any class you have and it will only create 1 instance per class.

    NOTE: You should always make the __construct private to eliminate the use of new Class(); instantiations.

提交回复
热议问题