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

Inject a function in controller so that its available to all controllers like initialize() function...?

I am trying to add a function in controller, kind of global function that is available to all controllers as well as models. Similar to addFunction() of volt compiler, is there a way we can add a function (may be thru dispatcher), so that the function is available to all the controllers, similar to controllers initialize() function. I have created a constants.php file, where i can create such function, but i was trying to find some other way to do it. What i am trying to do is, add a function say someTask(), and in all the controllers, i should be able to access it simply by calling someTask(). I hope this is clear. Can something like this be achieved..?

edited Dec '15

Hey, 3 solutions come to my mind:

1) If you want to access this function only from controllers create primary controller for example BaseController which other controllers extend. This way they will have access to the function defined in BaseController;

2) Add the function in your service, this way it will be available everywhere in your project (like procedural style);

3) Create a Helper class and add its namespace to Loader. Example code from project of mine:

        $namespaces = array(
            'Frontend\Controllers' => __DIR__ . '/controllers/', 
            'Frontend\Forms' => __DIR__ . '/forms/',
            'Models' => __DIR__ . '/../../common/models/', 
            'Helpers' => __DIR__ . '/../../common/helpers/', 
        ); 

In helpers i store code which i want to reuse and it does not belong to models or controllers. For example sending mails or stuff like that.