简体   繁体   中英

ZF2 Execute function before child routes that are in some modules

I have a route called student, like this

'student' => array(
 'type' => 'Hostname',
   'options' => array(
     'route' => ':subdomain.domain.com',
     'constraints' => array(
       'subdomain' => '([a-zA-Z0-9]*)'
         ...

And there are child routes in some of my modules. I need to run a function (eg checkSubdomain()) before execute any action of this child routes.

Anyone can help me?

Thank you guys! My code now:

public function onBootstrap(MvcEvent $e)
{
    $eventManager        = $e->getApplication()->getEventManager();

    $eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'checkSubdomain'));
    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);
}

public function checkSubdomain(EventInterface $e) {
    $app = $e->getApplication();
    $sm = $app->getServiceManager();
    $routeMatch = $e->getRouteMatch();
    $matchedRouteName = $routeMatch->getMatchedRouteName();


    $arr = explode('/',$matchedRouteName);
    if ($arr[0]=='student') {
        $subdomain = $routeMatch->getParam('subdomain');
        $em = $sm->get('project_entitymanager');
        $proj = $em->getRepository('Project\Entity\Project')->findOneBy(array('subdomain' => $subdomain));

        if (!$proj) $e->stopPropagation();
    }
}

Depending on what actually needs to be done in this 'check', I would attach an event listener to the MvcEvent::EVENT_ROUTE event or perhaps MvcEvent::EVENT_DISPATCH

For example

// Module.php
public function onBootstrap(MvcEvent $event) {
  $application  = $event->getApplication();
  $eventManager = $application->getEventManager();

  $eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'checkSubdomain'));
} 

public function checkSubdomain(EventInterface $event) {
   // Use $event to fetch the required event criteria
   // and 'check' sub domain here
}

You can do this in Module class's init function. In module/Application/Module.php and init

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