JasonDavis
JasonDavis

Reputation: 48933

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->storeObject("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?

Upvotes: 2

Views: 1042

Answers (4)

Crozin
Crozin

Reputation: 44376

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.

Upvotes: 1

jspcal
jspcal

Reputation: 51904

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.

Upvotes: 1

mr-sk
mr-sk

Reputation: 13407

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 ....

Upvotes: 1

Emil Vikstr&#246;m
Emil Vikstr&#246;m

Reputation: 91922

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.

Upvotes: 0

Related Questions