1

Possible Duplicate:
Is a good idea have a BaseController and make all controllers extend that class?

I would like to know the benefits/purposes why you should extend your controllers from a BaseController. I see people doing it, but I just don't know why.

Community
  • 1
  • 1
Eduard Luca
  • 6,514
  • 16
  • 85
  • 137
  • @DavidWeinraub not a duplicate of that. I was asking for the pros/cons of having this architecture implemented. – Eduard Luca Jan 14 '12 at 18:21

3 Answers3

1

Maybe you should take a look at this:

Extending Zend_Controller_Action

I personally extend my Controllers to add some custom functionality to my Controllers. Example: If check if the request is from a cron job or normal request. Sometimes I check for AJAX requests or disable debugging and profiling.

This is my init function:

       public function init() {

       parent::init();

       if (($this->getRequest()->getParam('type') == 'cron')||($this->getRequest()->getParam('type') == 'cmd') || ($this->getRequest() instanceof Zend_Controller_Request_Http &&  $this->getRequest()->isXmlHttpRequest() )) {

       Zend_Registry::get( 'debug' )->disable();
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender( true );
       }

}

It's really up to you what you want to do in your controllers.

Songo
  • 5,618
  • 8
  • 58
  • 96
1

I extended from a base controller in my first ZF project. In my opinion, it's not a bad approach if you know that all your subclasses will always actually use the same common functionality of the superclass.

In any case, for my following projects, I switched to using Action Helpers and Controller Plugins (see Zend Framework: Controller Plugins vs Action Helpers), and I never looked back. They look much more flexible to me, and allow me to reuse some features from project to project. It also adheres more to the "Prefer composition over inheritance" principle (there's a related question here: Prefer composition over inheritance?).

Hope that helps,

Community
  • 1
  • 1
dinopmi
  • 2,683
  • 19
  • 24
0

You can also use a BaseController to check for authorization using the preDispatch method, that is automatically called before the actual action:

public function preDispatch()
{
    $request = Zend_Controller_Front::getInstance()->getRequest();
    $controller = $request->getControllerName();

    if($controller == 'user') {
        return;
    }

    $auth = Zend_Auth::getInstance();
    if (! $auth->hasIdentity()) {
        $this->_helper->redirector("login_error", "user");
    }
}
Karlisson
  • 520
  • 4
  • 12