vendredi 10 août 2018

Patterns: Using an object to contain global objects, PHP

Ok, so I was wondering how to control objects that are unique and dependants for other objects - singletons perhaps, but not singletons. I don't always want all objects created each time this is executed, only when needed. So my system is you add a named object to a "manifest", along with a factory method. And you call the manifest when you want that named object, which creates the object if not already created, and returns it. Is there any downsides to this approach, is there a better way?

Here's the class for it

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'];
    }

}

Here's how it's used

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'));
    });

Aucun commentaire:

Enregistrer un commentaire