Wtyczki

Wprowadzenie

Architektura kontrolera zawiera także system wtyczek, który pozwala programiście na wykonanie własnego kodu, gdy następują określone zdarzenia w trakcie trwania procesu kontrolera. Kontroler frontowy używa agenta wtyczek jako rejeestru dla wtyczek programisty, a agent wtyczek jest odpowiedzialny za to, że metody zdarzeń są wywoływane dla każdej wtyczki zarejestrowanej w kontrolerze frontowym.

Metody zdarzeń są zdefiniowane w klasie abstrakcyjnej Zend_Controller_Plugin_Abstract, z której dziedziczy każda klasa wtyczki:

  • Metoda routeStartup() jest wywoływana zanim Zend_Controller_Front wywoła router w celu sprawdzenia żądania pod kątem zarejestrowanych tras.

  • Metoda routeShutdown() jest wywoływana po tym jak router zakończy routing żądania.

  • Metoda dispatchLoopStartup() jest uruchamiana zanim Zend_Controller_Front zacznie pętlę uruchamiania.

  • Metoda preDispatch() jest wywoływana zanim akcja zostanie uruchomiona przez obiekt uruchamiający. Pozwala to na stworzenie funkcjonalności proxy lub filtra. Nadpisując żądanie i resetując flagę uruchomienia (za pomocą Zend_Controller_Request_Abstract::setDispatched(false)), obecna akcja może być pominięta lub zastąpiona.

  • postDispatch() jest wywoływana po tym jak akcja zostanie uruchomiona przez obiekt uruchamiający. Pozwala to na stworzenie funkcjonalności proxy lub filtra. Nadpisując żądanie i resetując flagę uruchomienia (za pomocą Zend_Controller_Request_Abstract::setDispatched(false)), można określić nową akcję do uruchomienia.

  • Metoda dispatchLoopShutdown() jest wywoływana po tym jak Zend_Controller_Front zakończy pętlę uruchamiania.

Pisanie wtyczek

W celu napisania klasy wtyczki, w prosty sposób rozszerz klasę abstrakcyjną Zend_Controller_Plugin_Abstract:

class MyPlugin extends Zend_Controller_Plugin_Abstract
{
    // ...
}

        

Żadna z metod klasy Zend_Controller_Plugin_Abstract nie jest abstrakcyjna, co oznacza, że nie jest konieczne implementowanie wszystkich dostępnych metod zdarzeń opisanych powyżej. Autor wtyczki może zaimplementować tylko te metody zdarzeń, które są mu rzeczywiście potrzebne.

Zend_Controller_Plugin_Abstract udostępnia także obiekty żądania i odpowiedzi wtyczkom kontrolera za pomocą metod getRequest() oraz getResponse(), odpowiednio.

Użycie wtyczek

Klasy wtyczek są rejestrowane za pomocą metody Zend_Controller_Front::registerPlugin() i mogą być rejestrowane w dowolnym momencie. Poniższy kod pokazuje w jaki sposób wtyczka może być użyta przez kontroler:

class MyPlugin extends Zend_Controller_Plugin_Abstract
{
    public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
        $this->getResponse()->appendBody("<p>Wywołano metodę routeStartup()</p>\n");
    }

    public function routeShutdown(Zend_Controller_Request_Abstract $request)
    {
        $this->getResponse()->appendBody("<p>Wywołano metodę routeShutdown()</p>\n");
    }

    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        $this->getResponse()->appendBody("<p>Wywołano metodę dispatchLoopStartup()</p>\n");
    }

    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $this->getResponse()->appendBody("<p>Wywołano metodę preDispatch()</p>\n");
    }

    public function postDispatch(Zend_Controller_Request_Abstract $request)
    {
        $this->getResponse()->appendBody("<p>Wywołano metodę postDispatch()</p>\n");
    }

    public function dispatchLoopShutdown()
    {
        $this->getResponse()->appendBody("<p>Wywołano metodę dispatchLoopShutdown()</p>\n");
    }
}

$front = Zend_Controller_Front::getInstance();
$front->setControllerDirectory('/path/to/controllers')
      ->setRouter(new Zend_Controller_Router_Rewrite())
      ->registerPlugin(new MyPlugin());
$front->dispatch();

        

Zakładając, że żadne wywołana akcja nie wyświetliła żadnych danych, i że tylko jedna akcja została wywołana, to funkcjonalność powyższej wtyczki spowoduje wyświetlenie takich danych:

<p>Wywołano metodę routeStartup()</p>
<p>Wywołano metodę routeShutdown()</p>
<p>Wywołano metodę dispatchLoopStartup()</p>
<p>Wywołano metodę preDispatch()</p>
<p>Wywołano metodę postDispatch()</p>
<p>Wywołano metodę dispatchLoopShutdown()</p>

        

Uwaga

Wtyczki mogą być zarejestrowane w dowolnym momencie podczas uruchomienia kontrolera frontowego. Jednak jeśli zdarzenie dla którego we wtyczce była zarejestrowana metoda już minęło, to metoda ta będzie ominięta.

Wtyczki dołączone do standardowej dystrybucji

Zend Framework w standardowej dystrybucji zawiera wtyczkę służącą do obsługi błędów.

ActionStack

The ActionStack plugin allows you to manage a stack of requests, and operates as a postDispatch plugin. If a forward (i.e., a call to another action) is already detected in the current request object, it does nothing. However, if not, it checks its stack and pulls the topmost item off it and forwards to the action specified in that request. The stack is processed in LIFO order.

You can retrieve the plugin from the front controller at any time using Zend_Controller_Front::getPlugin('Zend_Controller_Plugin_ActionStack'). Once you have the plugin object, there are a variety of mechanisms you can use to manipulate it.

  • getRegistry() and setRegistry(). Internally, ActionStack uses a Zend_Registry instance to store the stack. You can substitute a different registry instance or retrieve it with these accessors.

  • getRegistryKey() and setRegistryKey(). These can be used to indicate which registry key to use when pulling the stack. Default value is 'Zend_Controller_Plugin_ActionStack'.

  • getStack() allows you to retrieve the stack of actions in its entirety.

  • pushStack() and popStack() allow you to add to and pull from the stack, respectively. pushStack() accepts a request object.

An additional method, forward(), expects a request object, and sets the state of the current request object in the front controller to the state of the provided request object, and markes it as undispatched (forcing another iteration of the dispatch loop).

Zend_Controller_Plugin_ErrorHandler

Zend_Controller_Plugin_ErrorHandler provides a drop-in plugin for handling exceptions thrown by your application, including those resulting from missing controllers or actions; it is an alternative to the methods listed in the MVC Exceptions section.

The primary targets of the plugin are:

  • Intercept exceptions raised when no route matched

  • Intercept exceptions raised due to missing controllers or action methods

  • Intercept exceptions raised within action controllers

In other words, the ErrorHandler plugin is designed to handle HTTP 404-type errors (page missing) and 500-type errors (internal error). It is not intended to catch exceptions raised in other plugins.

By default, Zend_Controller_Plugin_ErrorHandler will forward to ErrorController::errorAction() in the default module. You may set alternate values for these by using the various accessors available to the plugin:

  • setErrorHandlerModule() sets the controller module to use.

  • setErrorHandlerController() sets the controller to use.

  • setErrorHandlerAction() sets the controller action to use.

  • setErrorHandler() takes an associative array, which may contain any of the keys 'module', 'controller', or 'action', with which it will set the appropriate values.

Additionally, you may pass an optional associative array to the constructor, which will then proxy to setErrorHandler().

Zend_Controller_Plugin_ErrorHandler registers a postDispatch() hook and checks for exceptions registered in the response object. If any are found, it attempts to forward to the registered error handler action.

If an exception occurs dispatching the error handler, the plugin will tell the front controller to throw exceptions, and rethrow the last exception registered with the response object.

Using the ErrorHandler as a 404 Handler

Since the ErrorHandler plugin captures not only application errors, but also errors in the controller chain arising from missing controller classes and/or action methods, it can be used as a 404 handler. To do so, you will need to have your error controller check the exception type.

Exceptions captured are logged in an object registered in the request. To retrieve it, use Zend_Controller_Action::_getParam('error_handler'):

class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
        $errors = $this->_getParam('error_handler');
    }
}

Once you have the error object, you can get the type via $errors->type;. It will be one of the following:

  • Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE, indicating no route matched.

  • Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER, indicating the controller was not found.

  • Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION, indicating the requested action was not found.

  • Zend_Controller_Plugin_ErrorHandler::EXCEPTION_OTHER, indicating other exceptions.

You can then test for either of the first three types, and, if so, indicate a 404 page:

class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
        $errors = $this->_getParam('error_handler');

        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
                // 404 error -- controller or action not found
                $this->getResponse()
                     ->setRawHeader('HTTP/1.1 404 Not Found');

                // ... get some output to display...
                break;
            default:
                // application error; display error page, but don't
                // change status code
                break;
        }
    }
}

Finally, you can retrieve the exception that triggered the error handler by grabbing the exception property of the error_handler object:

public function errorAction()
{
        $errors = $this->_getParam('error_handler');

        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
                // 404 error -- controller or action not found
                $this->getResponse()
                     ->setRawHeader('HTTP/1.1 404 Not Found');

                // ... get some output to display...
                break;
            default:
                // application error; display error page, but don't change
                // status code

                // ...

                // Log the exception:
                $exception = $errors->exception;
                $log = new Zend_Log(
                    new Zend_Log_Writer_Stream(
                        '/tmp/applicationException.log'
                    )
                );
                $log->debug($exception->getMessage() . "\n" .
                            $exception->getTraceAsString());
                break;
        }
}
Handling Previously Rendered Output

If you dispatch multiple actions in a request, or if your action makes multiple calls to render(), it's possible that the response object already has content stored within it. This can lead to rendering a mixture of expected content and error content.

If you wish to render errors inline in such pages, no changes will be necessary. If you do not wish to render such content, you should clear the response body prior to rendering any views:

$this->getResponse()->clearBody();
Plugin Usage Examples

Przykład 155. Standard Usage

$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Zend_Controller_Plugin_ErrorHandler());

Przykład 156. Setting a Different Error Handler

$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Zend_Controller_Plugin_ErrorHandler(array(
    'module'     => 'mystuff',
    'controller' => 'static',
    'action'     => 'error'
)));

Przykład 157. Using Accessors

$plugin = new Zend_Controller_Plugin_ErrorHandler();
$plugin->setErrorHandlerModule('mystuff')
       ->setErrorHandlerController('static')
       ->setErrorHandlerAction('error');

$front = Zend_Controller_Front::getInstance();
$front->registerPlugin($plugin);

Error Controller Example

In order to use the Error Handler plugin, you need an error controller. Below is a simple example.

class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
        $errors = $this->_getParam('error_handler');

        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
                // 404 error -- controller or action not found
                $this->getResponse()->setRawHeader('HTTP/1.1 404 Not Found');

                $content =<<<EOH
<h1>Error!</h1>
<p>The page you requested was not found.</p>
EOH;
                break;
            default:
                // application error
                $content =<<<EOH
<h1>Error!</h1>
<p>An unexpected error occurred. Please try again later.</p>
EOH;
                break;
        }

        // Clear previous content
        $this->getResponse()->clearBody();

        $this->view->content = $content;
    }
}