CakePHP 3 - 使用单个控制器将参数传递给应用程序,所有请求都路由到它
CakePHP 3 - Passing parameters to application with a single controller where all requests are routed to it
CakePHP3.x
在路由文档 (https://book.cakephp.org/3.0/en/development/routing.html) 中说:
If you have a single controller in your application and you do not want the controller name to appear in the URL, you can map all URLs to actions in your controller. For example, to map all URLs to actions of the home controller, e.g have URLs like /demo instead of /home/demo, you can do the following:
$routes->connect('/:action', ['controller' => 'Home']);
这很好,因为这意味着我可以在 src/Controller/HomeController.php
:
中做这样的事情
public function foo()
{
// Accessible through URL "/foo"
}
public function bar()
{
// Accessible through URL "/bar"
}
但是如果我需要将参数传递给函数,例如
public function baz($a, $b, $c)
{
}
如果我调用以下任何 URL,它会给我一个 "Missing Controller" 错误:
/baz/2
/baz/2/17
/baz/2/17/99
说我需要创建"BazController"。
所有这些,都可以工作,因为它们包括控制器名称:
/home/baz/2
/home/baz/2/17
/home/baz/2/17/99
大概是路由问题吧?
有趣的是,调用 /baz
没有任何参数 工作正常。
@arilia 在评论中提供的正确答案是:
$routes->connect('/:action/*', ['controller' => 'Home']);
我的问题中提供的 URL 现在将按如下方式工作。所有这些都将映射到 HomeController.php
并执行 baz()
函数:
/baz/2
/baz/2/17
/baz/2/17/99
*
(在 app/routes.php
中 /:action/*
的末尾)是允许在 URL 中传递任意数量参数的关键。
CakePHP3.x
在路由文档 (https://book.cakephp.org/3.0/en/development/routing.html) 中说:
If you have a single controller in your application and you do not want the controller name to appear in the URL, you can map all URLs to actions in your controller. For example, to map all URLs to actions of the home controller, e.g have URLs like /demo instead of /home/demo, you can do the following:
$routes->connect('/:action', ['controller' => 'Home']);
这很好,因为这意味着我可以在 src/Controller/HomeController.php
:
public function foo()
{
// Accessible through URL "/foo"
}
public function bar()
{
// Accessible through URL "/bar"
}
但是如果我需要将参数传递给函数,例如
public function baz($a, $b, $c)
{
}
如果我调用以下任何 URL,它会给我一个 "Missing Controller" 错误:
/baz/2
/baz/2/17
/baz/2/17/99
说我需要创建"BazController"。
所有这些,都可以工作,因为它们包括控制器名称:
/home/baz/2
/home/baz/2/17
/home/baz/2/17/99
大概是路由问题吧?
有趣的是,调用 /baz
没有任何参数 工作正常。
@arilia 在评论中提供的正确答案是:
$routes->connect('/:action/*', ['controller' => 'Home']);
我的问题中提供的 URL 现在将按如下方式工作。所有这些都将映射到 HomeController.php
并执行 baz()
函数:
/baz/2
/baz/2/17
/baz/2/17/99
*
(在 app/routes.php
中 /:action/*
的末尾)是允许在 URL 中传递任意数量参数的关键。