phpzend-framework2zend-framework-routing

Can I have an action that doesn't load a template?


I got an answer to this question here, but now I have another concern\problem.

I have a subnav bar in my module created from a view partial via a helper. Here is the config in module.config.php:

'navigation' => array(
    'default' => array(
        array(
            'label' => 'Search',
            'route' => 'mymodule\search',
        ),
        array(
            'label' => 'Log Off',
            'route' => 'logout',
        ),
    ),
),

I have a LoginController with 2 actions: login and logout. After logging in I want the user to click the logout button, be redirected to the login page and have their session cleared.

Now if I have a login and logout action I need a template for each. This seems unnecessary for the logout action- I don't want another template to load for this action.

Here's my routing config:

'login' => array(
        'type' => 'Zend\Mvc\Router\Http\Literal',
        'options' => array(
                'route' => '/login',
                'defaults' => array(
                        '__NAMESPACE__' => 'Application\Controller',
                        'controller' => 'Application\Controller\Login',
                        'action' => 'login',
                ),
        ),
),
'logout' => array(
        'type' => 'Zend\Mvc\Router\Http\Literal',
        'options' => array(
                'route' => '/login',
                'defaults' => array(
                        '__NAMESPACE__' => 'Application\Controller',
                        'controller' => 'Application\Controller\Login',
                        'action' => 'logout',
                ),
        ),
),

Is there a correct way to have an action get called without loading a corresponding template?


Solution

  • You can return a response object instead:

    public function logoutAction()
    {
        // do stuff
    
        return $this->redirect()->toRoute('login');
    }
    

    then you don't need a template.