在 Zend Framework 3 中,是否可以根据 URL 是否包含查询字符串来路由到 Controller ?
例如,我有这两个网址:
/users
/users?name=Bob
我希望第一个路由调用 UsersController
,第二个路由调用 NameController
。
这可能吗?
最佳答案
我的评论正在变成一个答案。所以,给你。
下次请务必关注How to Ask .
请阅读 ZF3 docs on Router可能还有 RFC 3986 Chapter 3 - Syntax Components显示什么是路径,什么是查询。
来自 RFC 3986 Chapter 3 - Syntax Components
The following are two example URIs and their component parts:
foo://example.com:8042/over/there?name=ferret#nose \_/ \______________/\_________/ \_________/ \__/ | | | | | scheme authority path query fragment | _____________________|__ / \ / \ urn:example:animal:ferret:nose
ZF3路由配置一般是路径上的配置。 (几乎所有常见框架也是如此。) 是的,变量可以是路径的一部分。因此,它们是在路由配置中配置的。框架路由的高级配置通常还允许方案和权限中的更改/要求。
“查询”和“片段”部分不是路由配置的一部分。
如果你想做某事,例如捕获一个“名称”键/值对并相应地进行路由,您将必须在路径上创建一个“捕获器”(或任何名称)并自行确定重定向。
例如,您可以执行类似 this answer 的操作.如果您的 Controller 实例扩展了默认的 Zend Framework AbstractActionController
类,那么您应该拥有 forward
plugin可用的。来自文档:
Forward returns the results of dispatching the requested controller; it is up to the developer to determine what, if anything, to do with those results. One recommendation is to aggregate them in any return value from the invoking controller.
As an example:
$foo = $this->forward()->dispatch('foo', ['action' => 'process']);
return [
'somekey' => $somevalue,
'foo' => $foo,
];
当然,您可以立即返回。
另一个选项是 redirect
plugin (相同的链接)。
return $this->redirect()->toRoute('login-success');
有了这些你就可以做类似的事情了:
$name = $this->params()->fromQuery('name', null);
if ($name) {
// dispatch
if ($dispatchResult) {
// return special
}
}
// redirect
重定向到路由名称的地方(即配置的路径)
关于php - Zend Framework 3 - 基于查询字符串的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55597651/