开发者

Will a Registry Class in PHP work like this?

If I create a registry object to store other objects and settings in like this...

$registry = Registry::getInstance();

And then create 2 other objects and pass the Registry object into them like this below...

$core = new core($registry);
$database = Database::getInstance($registry);

and then later in the script I add some objects to the Registry object...

// Store some Objects into our Registry object using a Registry Pattern
$registry->s开发者_StackOverflow社区toreObject("database", $database);
$registry->storeObject("session", $session);
$registry->storeObject("cache", $cache);
$registry->storeObject("user", $user);

Will methods in the core and database objects that were created at the top, still have access to all the objects that I store into the registry even though the other objets were stored into the registry AFTER the core and database Objects were created?


yes they will, objects are passed by reference (in php >= 5) so, each variable will refer to the same underlying object.

in old php, you would need to pass by ref:

$obj->registry =& $registry;

function f(& $registry) { // $registry is a reference }

the key in php <5 is the ampersand syntax when assigning and in function declarations.


If its the same instance of the object, than yes - otherwise they'll have to use shared memory to pass the objects around or no, you won't have access to them.

However, I'd imagine your registry is a singleton right? So yes.

edit: maybe Im not understanding your question ....


Yes, they'll have access to these object, but IMO Registry isn't the best solution here - Context would be much better because it allows you to model each property. It also gives you 100% sure that when you call $registry->get('user') some User object will be returned.

Context is pretty similar to Registry:

class Context {
    protected $database;
    protected $user;
    protected $logger;

    public function setDatabse(PDO $database) {
       $this->database = $database;
    }

    public function getDatabase() {
       return $this->database;
    }

    public function setLogger(Logger $logger) {
       if ($logger instanceof MySpecificLogger) {
          // do sth
       }

       $this->logger = $logger;
    }

    // rest of setters/getters
}

And when you use it later:

$db = $contextObject->getDatabase();

When you use Registry you don't have 100% sure that $db is then an object of PDO (in this example) what might causes some problems in some situations.


No, not by default. Parameters are passed by value in PHP in almost every case. What you want is called "passing by reference", which you can read more about in the manual.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜