模式:使用对象包含全局对象,PHP

时间:2018-08-10 18:18:52

标签: php design-patterns

好,所以我想知道如何控制唯一且与其他对象相关的对象-也许是单例,但不是单例。我并不总是希望每次执行时都创建所有对象,仅在需要时才创建。因此,我的系统是将命名对象以及工厂方法添加到“清单”中。然后,在需要该命名对象时调用清单,清单对象将创建该对象(如果尚未创建)并返回它。这种方法是否有缺点,是否有更好的方法?

这是它的课程

class Manifest
{

    private static $man_objects=[];


    /**
     * Add manifest object
     *
     * Adds definition of object that might be global, or dependency of various
     * objects.
     *
     * @param string $name Name of Manifest object
     * @param callback $factory Callback to function that returns instance to be
     * stored in manifest.
     *
     */
    public static function AddManifestObject($name,$factory){
        self::$man_objects[$name]=['factory'=>$factory,'instance'=>null];
    }
    /**
     * Get manifest object
     *
     * Gets manifest object
     *
     * @param string $name Name of Manifest object to get
     * @throws Exception Throws exception if not found
     */
    public static function GetManifestObject($name){
        if(!isset(self::$man_objects[$name]))
            throw new Exception("Manifest object not found {$name}.");
        if(self::$man_objects[$name]['instance']===null)
            self::$man_objects[$name]['instance']=
                self::$man_objects[$name]['factory']();
        return self::$man_objects[$name]['instance'];
    }

}

使用方法

Manifest::AddManifestObject('MainDB',function(){
        $pdo=new \PDO("pgsql:host=localhost;port=5432;dbname=test;".
            "user=test;password=test");
        $pdo->setAttribute(\PDO::ATTR_ERRMODE,\PDO::ERRMODE_EXCEPTION);
        return $pdo;
    });
Manifest::AddManifestObject('AdminPrefs',function(){
        return new \Content\lib\AdminPrefs(
            Manifest::GetManifestObject('Language'));
    });
Manifest::AddManifestObject('Language',function(){
        return new \Content\lib\Language(
            Manifest::GetManifestObject('MainDB'));
    });
Manifest::AddManifestObject('Products',function(){
        return new \Content\lib\Products(
            Manifest::GetManifestObject('MainDB'));
    });

0 个答案:

没有答案