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

How to initialize on base controller

In a normal controller, it can use function intialize like this:

class GamesController extends ControllerBase
{
     public function initialize()
     {
         $this->view->disableLevel(View::LEVEL_MAIN_LAYOUT);
        ......
     }
}

But how to use initialize() function in Base Controller like this:

class ControllerBase extends Controller
{
    public function initialize()
    {   
        echo "hello";
    }
}
edited Mar '14

just call parent initialize method in each child class initializer method like below:

// in child class
public function initialize() 
{
    echo "hello"; 
    parent::initialize(); // call parent initializer too
}
edited Mar '14

or/and you can use onConstruct() method in your BaseController

class BaseController extends \Phalcon\Mvc\Controller 
{
    public function onConstruct() //this constructor/initializator is executed even if action isn't exist
    {
        echo "hello";
    }
}

Or you can use your own method, for e.g. 'init':

class ControllerBase extends \Phalcon\Mvc\Controller
{
     public function initialize()
     {
         $this->view->disableLevel(View::LEVEL_MAIN_LAYOUT);
        ......
        if (method_exists($this, 'init')) {
            $this->init();
        }
     }
}
class SomeController extends ControllerBase
{
    public function init()
    {

    }
}