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

Best way to run some code in every Controller action?

I'm currently trying out phalcon for the first time for a small static webpage + forms project.

I use the IndexController and have one action for each (currently static) route. I also have an addScripts() method inside the ControllerBase, that adds some css/javascripts with $this->assets->addCss() which are then output inside the main template via <? $this->assets->outputCss(); ?>

So far so good. Now I want to run the addScripts() method for each action, without having to copypaste the $this->addScripts() call into each action method. My first try was extendind the __construct() method of the ControllerBase class, which is final. So that doesn't work.

Then I checked out how events work, but this might be a little too much, as I might only want to inject the scripts in certain Controller classes, or at least have control over when exactly I inject those.

What would be the best solution?



2.9k
Accepted
answer
edited Apr '18

You can add $this->addScripts() to the initialize() method in the base controller. You should try not to use __construct() with Phalcon, use initialize() instead. If you want to use addScripts() only in some of the controllers, you could override the parent's initialize method in the controllers where you don't need it.

Not the most elegant solution, but it should work. :)



543

ah, excellent. that's exactly what I was looking for.

Thanks!

(Assuming your IndexController is Extending the ControllerBase) you can add the $this->addscripts to the onConstruct() of the Controllerbase itself and any controller that extends it will trigger that

If you want to have Initialize in the ControllerBase you can also do that and run it there. So you don't have to add the addScripts() to each controller