hit*_*han 2 cakephp cakephp-3.0
我试图在CakePHP3中使用前缀路由.我在/config/routes.php中添加了以下行.
Router::prefix("admin", function($routes) {
????// All routes here will be prefixed with ‘/admin‘
????// And have the prefix => admin route element added.
????$routes->connect("/",["controller"=>"Tops","action"=>"index"]);
????$routes->connect("/:controller", ["action" => "index"]);
????$routes->connect("/:controller/:action/*");
});
Run Code Online (Sandbox Code Playgroud)
之后,我创建了/src/Controller/Admin/QuestionsController.php,如下所示.
<?php
namespace App\Controller\Admin;
use App\Controller\AppController;
class QuestionsController extends AppController {
public function index() {
//some code here
}
}
?>
Run Code Online (Sandbox Code Playgroud)
最后我试图访问localhost/app_name/admin/questions/index,但我得到一个错误说,Error: questionsController could not be found.但是,当我大写控制器名称的第一个字母(即localhost/app_name/admin/Questions/index)时,它工作正常.我认为这很奇怪,因为没有前缀,我可以使用第一个字符未大写的控制器名称.这是某种错误吗?
ndm*_*ndm 10
在Cake 3.x中,路由不再默认变形,相反,您必须明确地使用InflectedRoute路由类,例如在默认routes.php应用程序配置中可以看到:
Router::scope('/', function($routes) {
// ...
/**
* Connect a route for the index action of any controller.
* And a more general catch all route for any action.
*
* The `fallbacks` method is a shortcut for
* `$routes->connect('/:controller', ['action' => 'index'], ['routeClass' => 'InflectedRoute']);`
* `$routes->connect('/:controller/:action/*', [], ['routeClass' => 'InflectedRoute']);`
*
* You can remove these routes once you've connected the
* routes you want in your application.
*/
$routes->fallbacks();
});
Run Code Online (Sandbox Code Playgroud)
您自定义路由不指定特定的路由类,因此使用默认Route类,而后备路由使用变形路由,这就是它没有前缀的原因.
因此,要么在URL中使用大写的控制器名称,要么使用类似的路由类InflectedRoute来正确转换它们:
Router::prefix('admin', function($routes) {
// All routes here will be prefixed with ‘/admin‘
// And have the prefix => admin route element added.
$routes->connect(
'/',
['controller' => 'Tops', 'action' => 'index']
);
$routes->connect(
'/:controller',
['action' => 'index'],
['routeClass' => 'InflectedRoute']
);
$routes->connect(
'/:controller/:action/*',
[],
['routeClass' => 'InflectedRoute']
);
});
Run Code Online (Sandbox Code Playgroud)
另见http://book.cakephp.org/3.0/en/development/routing.html#route-elements