简体   繁体   中英

Zend 2 equivalent of Laravel 4 Route Filter

I'm new to Zend 2, I started first with laravel and I need something to do that I know Laravel's Route Filter can solve but I'm using Zend 2.

Laravel Route Filter

I checked the documentation of Zend 2 and I can't seem to find it.

I need to do some logging and stuffs only on selected routes and I don't want to add that code on every actions of every routes because I have over 50 different routes here, but in laravel I could make use of route filter so that in selected routes, it will go first in the filter before going to that route.

In laravel's route:

Route::get('route1',array('before'=>'generic','uses'=>'GenericController@getIndex'));
Route::get('route2',array('before'=>'generic','uses'=>'GenericController@getIndex'));
Route::filter('generic', 'RouteFilter');

I have not used Laravel before, but I followed to the link and I am very afraid to say that,

No, it does not exist

You will have use the controller:

public function somethingAction()
{
   if (!condition true) {
      return $this->notFoundAction();
      // or return $this->redirect()->toRoute('MyRoute');
   }

   // Route is filtered
}

You can also attach a callback to the MvcEvent::EVENT_ROUTE event:

public function(MvcEvent $e)
{
    $e->getApplication()->getEventManager()->attach(MvcEvent::EVENT_ROUTE, function(EventInterface $e) {
        // check the route and do whatever you like
        $matchedRouteName = $event->getRouteMatch()->getMatchedRouteName();
        if ($matchedRouteName = 'admin')  {// or whatever you want to check
           // check if user is admin
        }
   });
}

Not only MvcEvent::EVENT_ROUTE , there are a lot of events triggered such as MvcEvent::EVENT_DISPATCH . You just need to attach a callback function! For, full list of all the Mvc Events, view this link!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM