Page 1 of 1

Globals vs Registry Objects

Posted: Wed Mar 11, 2009 1:50 pm
by kaisellgren
Hello,

I am at a point of deciding how to handle something rather important in my project. Passing objects and variables in a global scope is required. However, I have been trying to decide which approach to use: globals or registry objects.

A registry object basically holds the global variables:

Code: Select all

$reg = new registry;
$reg -> set('name' => 'val');
echo $reg -> get('name');
With globals:

Code: Select all

$GLOBALS['name'] = 'val';
echo $GLOBALS['name'];
When we are using a registry object, the object has to be global too... so it kind of defeats the purpose of the whole object ?

How do you handle globals in your project. For instance, if you have a DB class that utilizes a cache class, do you just do "global $cache;" or what?

Re: Globals vs Registry Objects

Posted: Wed Mar 11, 2009 2:21 pm
by pickle
The registry wouldn't necessarily have to be global. You could use a singleton pattern to have import a copy of your registry. For example:

index.php

Code: Select all

<?php
require 'Registry.php';
require 'DB.php';
 
$Registry = Registry::getInstance();
$Registry->username = 'blah';
$Registry->password = 'humbug';
$Registry->db = 'mydb';
 
$DB = new DB();
?>
DB.php

Code: Select all

<?php
class DB
{
  function __construct()
  {
    $Registry = Registry::getInstance();
    mysql_connect('localhost',$Registry->username,$Registry->password,  $Registry->db);
  }
}
?>
There's really nothing wrong with using globals per se. My professors always warned against using them because if you see $username in a script somewhere, you don't really know where $username is defined if globals are being used. Generally I don't use globals, but I use constants quite often.

Re: Globals vs Registry Objects

Posted: Wed Mar 11, 2009 2:45 pm
by allspiritseve
kaisellgren wrote:I am at a point of deciding how to handle something rather important in my project. Passing objects and variables in a global scope is required. However, I have been trying to decide which approach to use: globals or registry objects. When we are using a registry object, the object has to be global too... so it kind of defeats the purpose of the whole object ?
Pass an instance of the registry in the constructor of your classes. That makes it less global than if you implement it as a singleton. Also, you don't have to pass this in every class. If you know a class doesn't have many dependencies (like a Gateway or ActiveRecord class, that may only need a DB connection), just pass those dependencies and not the registry.

Re: Globals vs Registry Objects

Posted: Wed Mar 11, 2009 3:07 pm
by kaisellgren
Thank you. Very useful information.