如何检查Controller Plugin preDispatch中是否存在操作

时间:2013-08-01 08:24:24

标签: php zend-framework zend-controller-plugin

我有两个模块(默认和移动)模块移动是重写jquery mobile中的默认门户,但控制器和操作少得多! 我想写一个控制器插件,检查模块移动设备中是否存在控制器和操作,如果不是,我想将模块移动设备覆盖为默认值。 我试试这个:

public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
    $dispatcher = Zend_Controller_Front::getInstance()->getDispatcher();
    if ($request->getModuleName() == 'mobile') {      
        if (!$dispatcher->isDispatchable($request)) {
            // Controller or action not exists
            $request->setModuleName('default');
        }
    }
    return $request;
}

$dispatcher->isDispatchable($request)始终返回true,但操作不存在! :S 我收到“行动foo不存在且未被困在__call()”

我该怎么办? 感谢

2 个答案:

答案 0 :(得分:0)

你有没有想过如何从应用程序的任何一侧检查zend FM中是否存在控制器/操作?这是代码

    $front = Zend_Controller_Front::getInstance();
    $dispatcher = $front->getDispatcher();

    $test = new Zend_Controller_Request_Http();
    $test->setParams(array(
        'action' => 'index',
        'controller' => 'content',

            )
    );

    if($dispatcher->isDispatchable($test)) {
        echo "yes-its a controller";
        //$this->_forward('about-us', 'content'); // Do whatever you want
    } else {
        echo "NO- its not a Controller";
    }

修改

像这样检查

$classMethods = get_class_methods($className);
 if(!in_array("__call", $classMethods) &&
 !in_array($this->getActionMethod($request), $classMethods))
 return false;

另请参阅detail link

答案 1 :(得分:0)

我建议您通过配置资源管理器,引导程序或前端控制器插件创建静态或动态路由:

在Bootstrap.php中定义静态路由的示例:

public function _initRoutes()
{
    $front = Zend_Controller_Front::getInstance();
    $router = $front->getRouter(); // default Zend MVC routing will be preserved

    // create first route that will point from nonexistent action in mobile module to existing action in default module
    $route = new Zend_Controller_Router_Route_Static(
        'mobile/some-controller/some-action', // specify url to controller and action that dont exist in "mobile" module
        array(
            'module' => 'default', // redirect to "default" module
            'controller' => 'some-controller',
            'action' => 'some-action', // this action exists in "some-controller" in "default" module
        )
    );
    $router->addRoute('mobile-redirect-1', $route); // first param is the name of route, not url, this allows you to override existing routes like default route

    // repeat process for another route
}

这样可以有效地将 / mobile / some-controller / some-action 的请求路由到 / default / some-controller / some-action

应该用适当的控制器和操作名称替换

some-controller some-action

我正在使用静态路由,如果您路由到确切的网址,这是可以的,但由于大多数应用程序在网址中使用额外的参数来控制器操作使用,因此最好使用动态路由。 在上面的示例中,只需将路由创建类更改为Zend_Controller_Router_Route并将URL路由到"mobile/some-controller/some-action/*",并且每个请求都将动态路由,如下所示:

/mobile/some-contoller/some-action/param1/55/param2/66 
will point to 
/default/some-controller/some-action/param1/55/param2/66

有关在ZF1中路由的详细信息,请检查this link