Raffael Luthiger
Raffael Luthiger

Reputation: 2211

Initialize a model in Zend Framework

According to this blog post it should be possible to have an init() method within the model. Like this:

class MyModel
{
    public function init()
    {
        // prepare something
    }   

... 
}

This does not work for me. Does anybody know if I have to set somewhere a parameter (e.g. in the config file) or if this is not possible any more in my Zend FW version (1.11.4)? I checked with error_log('something') within the init method and it does not get called at all.

UPDATE: I have extended Adam's solution a little:

public function __construct() {
    if (get_parent_class($this) != false) {
        parent::__construct();
    }
    if(method_exists($this, 'init')) {
        $this->init();
    }
}

This way it can be placed in a base class and then extended. Just in case someone needs the same solution later too.

Upvotes: 2

Views: 2418

Answers (3)

Tjorriemorrie
Tjorriemorrie

Reputation: 17282

you have that problem because a php class does not have an init method. That init method is only applicable to Zend classes. Which mean you can only use it when you extend a Zend class. Which means you are actually overriding the init method.

E.g. here it is in the Zend_Db_Table_Abstract class:

/**
 * Initialize object
 *
 * Called from {@link __construct()} as final step of object instantiation.
 *
 * @return void
 */
public function init()
{
}

So if you change your model to extend zend it will work:

class MyModel extends Zend_Db_Table_Abstract
{
    public function init()
    {
        // prepare something
    }   

... 
}

It's the same with Zend_Controller_Action, which is why you can also use it in your controllers.

Upvotes: 2

Tim Fountain
Tim Fountain

Reputation: 33148

That post is very misleading. If the model classes in the application extend Zend_Db_Table or Zend_Db_Table_Row, which is not the case in the post's examples but is implied from the text, then yes you can add an init() method that will be called automatically. For this to work in your application you would need to be calling the method from whatever creates your models, or from the constructor of a base class.

Upvotes: 4

Adam Pointer
Adam Pointer

Reputation: 1492

Try adding a call to init() from the constructor as so:

public function __construct()
{
  parent::__construct();
  $this->init();
}

Upvotes: 2

Related Questions