We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Difference between beforeExecuteRoute and initialize

Hello,

I'm having a hard time getting the difference between the beforeExecuteRoute and initialize Dispatcher events. The doc confuses me because :

  • about beforeExecuteRoute, it says that "at this point the dispatcher has [...] initialized the controller". So why does the initialize event come after?
  • about initialize, it does not say "Triggered when...", so I don't know what has happened since beforeExecuteRoute

Can anyone tell me, simply, what happens between those two events?



21.8k
Accepted
answer
edited Apr '14

The short answer :

Init runs every time a controller is instancied beforeExecuteRoute runs everytime an action is triggered.

Then in the case you forward to another action. beforeExecuteRoute will run, but init will run ONLY if you forwarded to a new controller.

But I have no answer why init is triggered after beforeExecuteRoute. Maybe an issue, or maybe it is an expected behaviour.... Dunno

The "a few longer answer" :

Actually lets setup the following structure :

controller1 with actions : act1 - act2 - act4 controller2 with actions : act3

Let's say that each action forwards to the next one. Then when we call controller1/act1 we do the following job :

controller1::act1 => controller1::act2 => controller2::act3 => controller1::act4

Then the following will be triggered :

  • BeforeExecuteRoute (controller1 act1)
  • Initialize (controller1)
  • act1 -> forward to controller1:act2
  • BeforeExecuteRoute (controller1 act2)
  • // NO init on contorller 1 becausse already done
  • act2 -> forward to controller2:act3
  • BeforeExecuteRoute (controller2 act3)
  • Initialize (controller2)
  • act3 -> forward to controller1:act4
  • BeforeExecuteRoute (controller1 act4a)
  • // NO init on contorller 1 becausse already done


8.2k

Thank you Sofiane for a very clear answer.