I’m trying to find a way to hold all the php application data at one place.
For example,get and post parameters, page titles, pagination results, etc. to avoid using global variables.
Is this a good idea to keep all data and exchange between contollers in a following object?
class container {
protected static $_instance;
protected $_instance_class;
public static function instance($instance_name = 'default')
{
$c = __CLASS__;
if ( ! isset($c::$_instance[$instance_name]))
{
$c::$_instance[$instance_name] = new $c();
$c::$_instance[$instance_name]->_instance_class = $instance_name;
}
return $c::$_instance[$instance_name];
}
public function set($key, $val)
{
// someting like $this->$key = $val;
}
public function get($key)
{
// someting like retrun $this->$key;
}
}
and then, for example in model
container::instance('messages')->set('error', 'some error');
and in the controller or view
container::instance('messages')->get('error');
Or is there any other way to keep data accessible from everywhere in the app?
thanks!
What you’re talked about is called Registry pattern (and another good article on it). While it has some disadvantages (for example, to test a method that fetches some data from Registry we have to mock this Registry as well), it’s definitely better than using global variables or Singletons.
In fact, in Zend Framework 1 this pattern is implemented quite literally:
To show what can be wrong with this approach, let’s analyze the following:
The question is simple: what’s that
$bazthing here? Is it an object? Or array? Or some other beast, like function or resource? You have to rely on comments here, and that’s usually not a good thing – unless you’re working with trivial and common objects (like query params, or database resource objects).