开发者

Dynamically build a class member variable

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 开发者_如何学Cwant to create my models ignorants of their dependencies?


Use arrays

class Foo {
  private $_data = array();


  protected function _initDependency()
  {
    $this->_table = null;

    foreach (self::$_staticDependency as $key => $dependency) {
      $varName = '_' . $key;
      $this->_data[$varName] = new $dependency();
    }
  }
}

(As a side effect this also removes the variable-variables)

You can use __get(), __set(), __isset() and __unset() to simulate the property-behaviour.


Have you tried to consider any proper ORM like Doctrine2. You save yourself time to reinvent the wheel. Doctrine2 is easy to set up with ZF and there is a lot of information on the net in case you get stuck.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜