Registry or Singleton pattern in PHP?

前端 未结 3 1745
慢半拍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:19

    That depends on your application. If you still need 3 out of the 4 classes, then it'd be more ideal to use the Registry than to handle the 3 independently only because you don't need the fourth. Loading the classes lazily would be one approach to reduce memory footprint, but then you need to instruct the registry when to create the objects and that's not much different than handling singletons. Alternatively, you could create an n-parameter constructor or use an array to instruct your Registry which classes to instantiate during construction.

    class Registry {
        public $class1;
        public $class2;
    
        function __construct($uses) {
            foreach($uses as $class) {
                $this->{$class} = new {$class}();
            }
        }
    
    }
    

    Then instantiate your Registry by specifying which classes to instantiate.

    $reg = new Registry(array('class1'));
    

    You would obviously want your constructor to handle zero parameters to account for instantiating all classes by default.

提交回复
热议问题