0

I want to do some actions before executing a controller method. But I can't because the initialize() method doesn't work in a micro application. I can check the way in Base controller and do some actions, but I think it is not valid.

Timothy
  • 2,004
  • 3
  • 23
  • 29
  • Please, show us how are you trying to use the initialize method? In other words: give us the code! – Luke Sep 01 '16 at 08:27

2 Answers2

3

You can't overwrite the __construct() method of Phalcon\Mvc\Controller because the __construct() is defined as final and therefor can't be altered.

A workaround is to let your baseController extend like this (instead of Phalcon\Mvc\Controller):

class BaseController extends \Phalcon\DI\Injectable {
    public function __construct() {
        // ...
    }
}

class YourController extends BaseController {
    // do stuff
}

Or instead of the above shenanigans, you could use the build-in method onConstruct

class BaseController extends Phalcon\Mvc\Controller {
    public function onConstruct() {
        // ...
    }
}

Note that the onConstruct() method triggers when the controller is created. This is different to the behaviour of the initialize() method, which triggers after beforeExecuteRoute().

Timothy
  • 2,004
  • 3
  • 23
  • 29
  • I extend Controller, not \Phalcon\DI\Injectable. And I find solution - I use onConstruct in BaseController and parent::onConstruct in controller that extends BaseController, but thanks. – Александр Ковальчук Sep 01 '16 at 09:22
  • @АлександрКовальчук, yes you should definitely use `onConstruct`. I think my eye caught onto Juri his answer, so I thought you were trying to use `__onConstruct()`. My bad :) – Timothy Sep 02 '16 at 06:42
0

Yes because controllers in micro are only handlers. Use __construct maybe ?

Juri
  • 1,369
  • 10
  • 16