I'm reading a book on ZF2 and it refers to both init() and onBootStrap() as functions in Module.php that are called during every page load and therefore should be as lightweight as possible.
Aside from a slightly different signature:
init(ModuleManager m)
onBootStrap(MvcEvent e)
I'm struggling to determine when I should use which, and for what reason. In the book, both methods are being used to attach to (different) events. Can someone provide a clear definition of the difference between the two, and some concrete examples where I would use one but not the other (and why)?
Thanks!
The answer to your question is a matter of timing and purpose. The init()
function always occurs before the onBootstrap()
function. Since the purpose of init()
is to initialize the module (eg. with its own, independent configuration options), other modules may not have been loaded at the time init()
is run for a given module. However, onBootstrap()
is run after all modules have been initialized, and it can listen for different events.
A much more thorough explanation of this can be found at http://framework.zend.com/manual/2.3/en/modules/zend.module-manager.module-manager.html and the next page in the documentation http://framework.zend.com/manual/2.3/en/modules/zend.module-manager.module-class.html
Personally, I use the init()
to initialize a Propel library in one module I creatively named Propel
by using the technique at http://4zend.com/integrate-propel-orm-with-zend-framework-2/.
I use onBootstrap()
to check my access control list (which users have access to what resources) and restrict access accordingly, like this:
public function onBootstrap(\Zend\Mvc\MvcEvent $e) {
// After the route event occurs, run the checkAcl method of this class
$e->getApplication()->getEventManager()->attach('route', array($this, 'checkAcl'));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With