Registry or Singleton pattern in PHP?

前端 未结 3 1725
慢半拍i
慢半拍i 2021-01-11 19:52

I am working with PHP classes and objects now. In this question the names of fields and methods are made up just so you get an idea of what I am talking about.

It

3条回答
  •  孤城傲影
    2021-01-11 20:18

    You can implement lazy loading to only load the objects you really need:

    class Registry
    {
        private static $database = null;
    
        private static function connectDatabase($key)
        {
            [... do connection stuff ...]
        }
    
        public static function getDatabase($key)
        {
            if (Registry::$database == null)
            {
                Registry::connectDatabase($key);
            }
            return Registry::$database;
        }
    }
    

    The code to register the database connection parameters is left as exercise to the reader.

提交回复
热议问题