Tuesday, May 18, 2010

Using the front controller


In this example, we instantiate a front controller and we dispatch an action. We also create a default controller. We customize the response to trace the calls. We have a plugin to set the default value of a parameter.

Components used in this example
Using the front controller

class MyFrontController
{
    const 
BASE_URL 'http://domain/subpath/';

    public static 
$uri = array(
        
'',
        
'my/',
        
'my/get/',
        
'my/get/param/123',
    );
Processing the front controller request
  • We get the URI.
  • We create the front controller.
  • We create the request.
  • We dispatch the action.
  • We extract the call trace from the response.
  • If we catch an exception, we return the error message.

    public function process()
    {
        
// We get the URI.
        
list($uri) = $this->_getParameters();

        try {
            
// We create the front controller.
            
$front Zend_Controller_Front::getInstance();
            
$front->setControllerDirectory('.')
                ->
returnResponse(true)
                ->
setParam('noViewRenderer'true)
                ->
setDefaultControllerName('default')
                ->
setDefaultAction('default')
                ->
setBaseUrl('/subpath')
                ->
registerPlugin(new MyPlugin);

            
// We create the request.
            
$request = new Zend_Controller_Request_Http(self::BASE_URL $uri);

            
// We dispatch the action.
            
$response $front->dispatch($request, new MyResponse);
            
// We extract the call trace from the response.
            
$result $response->getTrace();


        } catch (
Exception $e) {
            
// If we catch an exception, we return the error message.
            
$result $e->getMessage();
        }

        return array(
$uri$result);
    }
Extraction of the parameters from the GET request

    private function _getParameters()
    {
        
$uri = isset($_GET['uri'])? $_GET['uri'] : '';

        return array(
$uri);
    }

}

No comments:

Post a Comment