I want to extend all my controllers by different ParentControllers specified for each module separately.
And I don’t know, where to place the extended controller, and what to write in the top level controller.
I want to do something like that:
module/Application/src/Application/Controller/IndexController.php
namespace Application\Controller;
use Application\Controller\ApplicationHeadController;
class IndexController extends ApplicationHeadController {
public function indexAction() {
}
}
module/Application/src/Application/ApplicationHeadController
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
class ApplicationHeadController extends AbstractActionController {
public function init() {
parent::init();
// some common code for every controller in this module
}
}
I agree with Alex here: try not using overloading for this kind of task. Overloading (ie, using (abstract) classes and exstend them with your specific controller) creates difficulties at a later time.
For instance, what if one controller in the future should not execute that common code? You need to create logic to disable the execution of that common code with a flag in the constructor or something uglier. Or if you want to create a REST interface and one controller must extend the
AbstractRestfulControllerinstead of theAbstractActionController?Zend Framework 2 provides hooks where you can do this kind of work much more flexible. A “listener” is such hook for an “event” triggered. A controller sends out several events where you can listen to in your module class. One of them is “dispatch”, which is called when your
fooAction()methods run.You listen to the
dispatchevent inside the group of events fromMyModule. You can read more about the event manager and the module class.