zf2数据库驱动的页面,从单个动作动态处理

时间:2014-02-17 10:45:21

标签: zend-framework2

如何在ZF2中对我的所有数据库驱动(CMS)页面使用单个动态操作?

如果某个操作不存在,则应由dbpageAction()提供。

我在单个控制器中有以下路由(及其相关的控制器操作):

  • /contactus(contactusAction)
  • /sitemap(sitemapAction)
  • /home(dbpageAction)
  • /aboutus(dbpageAction)
  • /abcpage(dbpageAction)

任何其他数据库生成的页面也应由dbpageAction()

提供

2 个答案:

答案 0 :(得分:0)

一种方法是在控制器中使用notFoundAction

 public function notFoundAction() {
        echo "Action does not exist";
        //Your code here
    }

答案 1 :(得分:0)

有几种方法可以做到这一点。我会将事件管理器与MvcEvent::EVENT_DISPATCH_ERROR事件一起使用。

以下示例未经测试;然而,Matthew Weier O'Phinney有一个例子re-dispatching a controller action from within an event listener

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

  $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, function($event) use ($eventManager) {
     $response = $event->getParam('Response');

     // Check the response is a 404
     if (Response::STATUS_CODE_404 === $response->getStatusCode()) {

       // Create a new route match for the target route
       $routeMatch = new RouteMatch(array(
         'controller' => 'MyModule\Controller\Foo', // The controller name to use
         'action'     => 'dbPageAction', 
       ));
       // Clone the event and set our new route match
       $newEvent = clone $event;
       $newEvent->setRouteMatch($routeMatch);

       // now dispatch the controller action
       $eventManager->trigger(MvcEvent::EVENT_DISPATCH, $newEvent);

     }
  });
}

请记住,如果新调度的控制器/操作也会导致404,那么您可能会发现无限循环的未找到错误。