php - Zend Framework 2 段路由需要段

标签 php routing zend-framework2 zend-route zend-framework-routing

我正在尝试创建一个(或两个)路由,让我使用以下 URL 格式调用两个不同的操作。

mydomain.com/profile
mydomain.com/profile/1234/something

对于第二种格式,1234 应该是一个必需的整数值,而 something 应该是一个可选的字符串。第一种格式很简单,使用文字路由。我以为我可以为第二种格式添加一个段子路由,但我无法让它工作。我试图省略第一种格式,只使用分段路由来处理第二种格式,但我也没有成功。

这是我尝试过的:

'profile' => array(
    'type' => 'Zend\Mvc\Router\Http\Literal',
    'options' => array(
        'route' => '/profile',
        'defaults' => array(
            'controller' => 'User\Controller\User',
            'action' => 'profile'
        )
    ),
    'child_routes' => array(
        'profile_view' => array(
            'type' => 'Zend\Mvc\Router\Http\Segment',
            'options' => array(
                'route' => '/:code[/:username]',
                'constraints' => array(
                    'code' => '[0-9]*',
                    'username' => '[a-zA-Z0-9_-]*'
                ),
                'defaults' => array(
                    'controller' => 'User\Controller\User',
                    'action' => 'view_profile'
                )
            )
        )
    )
)

对于 mydomain.com/profile,我收到以下错误:

Fatal error: Uncaught exception 'Zend\View\Exception\RuntimeException' with message 'No RouteMatch instance provided'

对于 mydomain.com/1234/something,我收到以下错误:

Fatal error: Uncaught exception 'Zend\Mvc\Router\Exception\InvalidArgumentException' with message 'Missing parameter "code"'

manual states the following :

If a segment is optional, it should be surrounded by brackets. As an example, “/:foo[/:bar]” would match a “/” followed by text and assign it to the key “foo”; if any additional “/” characters are found, any text following the last one will be assigned to the key “bar”.

这不正是我在做的吗?如果我注释掉约束,上述错误仍然存​​在。

我在这里错过了什么?提前致谢。

最佳答案

我的解决方案:将可选参数的默认值设置为空字符串

我遇到了类似的问题,我通过设置可选参数的默认值解决了这个问题(在你的情况下“用户名”为空字符串“”;我的解决方案:

'users' => array(
    'type' => 'segment',
    'options' => array(
        'route' => '/users[/:user_id]',
        'constraints' => array(
            'user_id' => '[0-9]*',
        ),
        'defaults' => array(
            'controller' => 'My\Controller\User',
            'user_id' => ""
        )
    ),

关于php - Zend Framework 2 段路由需要段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15045322/

相关文章:

php - 如何正确下载 .vcf 文件

c# - webform 中的 asp.net 路由 - 如何获取路由数据

javascript - Angular 2 : defining a Router on another Component than the bootstraped one

带有url参数的Angular 2路由与其他路由冲突

php - 在没有模板的情况下在 Zend Framework 2 中进行重定向

php - 如何在 Zend Framework 2 中向表单添加错误消息?

javascript - PHP 和 jQuery 与 AJAX 上传不工作

php - Symfony 4 和 mongodb :generate:documents

带有PDF输出的PHP PDF模板库?

sql-server - 通过 Linux 从 Zend2 访问 MSSQL