【问题标题】:Problem with Zend and addRoute()Zend 和 addRoute() 的问题
【发布时间】:2012-05-09 18:22:11
【问题描述】:

使用此代码:

$frontController = Zend_Controller_Front::getInstance(); 
$router = $frontController->getRouter();
$router->addRoute(
    'test',
    new Zend_Controller_Router_Route(
        '/test/:action/:type/:id',
        array(
            'controller' => 'admin'
        )
    )
);

http://app/test/param1/param2/param3 -> 好的

http://app/test/param1/param2/ -> 失败

在第二种情况下,应用程序无法识别 param2。

似乎应用程序需要 param3 才能读取 param2...

我该怎么做?

谢谢!


使用来自@RageZ 的代码进行测试

$frontController = Zend_Controller_Front::getInstance(); 
$router = $frontController->getRouter();
$router->addRoute(
    'test',
    new Zend_Controller_Router_Route(
        '/test/:action/:type/:id',
        array(
            'controller' => 'admin',
            'id' => 0
        ),
        array(
            'id' => '\d+'
        )
    )
);

http://app/test/ -> 好的

http://app/test/some -> 好的

http://app/test/some/more -> 失败

http://app/test/some/more/andmore -> 好的

想法?

【问题讨论】:

  • 最后一个代码缺少类型的默认值... ;)

标签: zend-framework zend-route


【解决方案1】:

尝试为所有内容设置默认值

$frontController = Zend_Controller_Front::getInstance(); 
$router = $frontController->getRouter();
$router->addRoute(
    'test',
    new Zend_Controller_Router_Route(
        '/test/:action/:type/:id',
        array(
            'controller' => 'admin',
            'action' => 'index',
            'type' => 'sometype',
            'id' => 0
        ),
        array(
            'id' => '\d+'
        )
    )
);

刚刚在某个测试项目中尝试了您的代码,这已修复,希望它对您有用!

【讨论】:

    【解决方案2】:

    如果参数是可选的,则必须提供默认值。

    $frontController = Zend_Controller_Front::getInstance(); 
    $router = $frontController->getRouter();
    $router->addRoute(
        'test',
        new Zend_Controller_Router_Route(
            '/test/:action/:type/:id',
            array(
                'controller' => 'admin',
                'id' => 0
            ),
            array(
                'id' => '\d+'
            )
        )
    );
    

    与您的问题无关,但使用 addRoute 的第三个参数是一个好习惯。 Zend Framework 将验证参数值是否与您指定的格式匹配,在这种情况下,我认为 id 是一个整数。

    【讨论】:

    • @joanballester:由您决定是否需要默认值并指定格式。在您的情况下,两个网址都可以使用
    • 对不起,但是……我不能!我会继续尝试(我已经编辑了帖子)
    • @joanballester:让我设置一个虚拟应用程序进行测试
    猜你喜欢
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 2015-10-01
    • 2011-08-18
    • 1970-01-01
    相关资源
    最近更新 更多