Search code examples
phpzend-frameworkcode-reuse

How do I reuse code in Zend Framework


I am working on a web application which requires the user to login before they see or do anything. No part of this app should be accessible without being logged in. (Except of course, the login controller)

Currently I am using sessions to handle the authentication and I have put code in each controller in the init() function to check if their session is valid.

This was a temporary workaround, but it is redundant and inefficient.

I would like my init() function to be similar to the following, but I am not sure how to achieve it:

public function init()
{
    // If user not logged in redirect to login controller
    $myLibrary = Zend_Library_MyLibrary();
    $myLibrary->CheckAuth();
}

So my question really has two parts:

  1. Where is the best place to store code that will be used in multiple controllers?
  2. How do I then call that function from a controller?

Thanks.


Solution

  • Code that is reused across multiple controllers is best placed into an ActionHelper. However, for your case, I suggest to write a Controller plugin. Those hook into the Dispatch process at various stages:

    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        if(!Zend_Auth::getInstance()->hasIdentity())
        {
            $request->setControllerName('auth');
            $request->setActionName('login');
            // Set the module if you need to as well.
        }
    }
    

    The above assumes you are using Zend_Auth to authenticate and manage your user identities.

    You want a plugin over a helper, because checking if the user is logged in should happen automatically, without you having to call a checkAuth() method somewhere. Of course, nothing stops you to add an ActionHelper too, e.g.

    class My_Helper_CheckAuth extends Zend_Controller_Action_Helper_Abstract
    {
        public function checkAuth()
        {
            return Zend_Auth::getInstance()->hasIdentity();
        }
        public function direct()
        {
            return $this->checkAuth();
        }
    }
    

    Once you registered your helper in the bootstrap, you could use it in every controller to check if the user is already authenticated:

    if ( $this->_helper->checkAuth() === FALSE) {
        // do something
    }
    

    Also see these tutorials: