I am trying to setup my php (Zend Framework) project through injection dependence. So far when I instanciated a model, I would pass the table and the view (database view) to my model like that:
$table = new My_Table();
$view = new My_View();
$model = new My_Model($table, $view);
All my models extends a Same class that take care of the construction, message handling and getters for forms to interact with the model.
Now I have to inject a model into a model and I was looking for a passive static way of doing this. In my model’s parent class I have added a static method inject which is called in the application bootstrap. I pass two string in the form of key => value where the key is the name of the variable that have to be created in the model and the value is the string that represents the class to be instanciated.
My_Model::inject('dependentModel', 'My_Other_Model')
The issue arise when I try to use the key as a new member variable through the following code :
protected function _initDependency()
{
$this->_table = null;
foreach (self::$_staticDependency as $key => $dependency) {
$varName = '_' . $key;
$this->{$$varName} = new $dependency();
}
}
I get the following message
Notice: Undefined variable: _dependentModel
What would be the best way to achieve that, knowing that I want to create my models ignorants of their dependencies?
Use arrays
(As a side effect this also removes the variable-variables)
You can use
__get(),__set(),__isset()and__unset()to simulate the property-behaviour.