Models in Zend Framework – Initialize All Methods with init()

In the Zend Framework’s documentation there are lots of examples how you can initialize all the actions in a given controller – by simply adding the init() public method in the controller’s code:

<?php
 
class IndexController extends Zend_Controller_Action
{
	public function init()
	{
		echo 'foo';	
	}	
 
	public function indexAction()
	{
		// first the 'foo' string will be printed
		echo 'bar';	
	}
}

But did you know that you can do the same thing with any model in ZF? However you can setup a cache for every method or something else, but definitely it will execute for every method:

<?php
 
class MyModel
{
	public function init()
	{
		// prepare the cache setup
	}	
 
	public function readAll()
	{
		// the cache is already setup
		$sql = '...';
		// ...
	}
}

Of course that means that directly calling the readAll() function the init() method is called also – automatically.

Conclusion

There are good and bad parts about this. You’ll have this code executed for every method and if you have twenty of them and the init() method is practically used for only a couple of the member functions – than this will be useless.

2 thoughts on “Models in Zend Framework – Initialize All Methods with init()

  1. Pingback: abcphp.com

Leave a Reply

Your email address will not be published. Required fields are marked *