cakephp - 路由: 'admin' => true vs 'prefix' => 'admin in CakePHP

标签 cakephp routing routes cakephp-1.3

嗨,我正在 CakePHP 中设置管理路由。

这是我目前的路线:

Router::connect('/admin/:controller/:action/*', array('admin' => true, 'prefix' => 'admin', 'controller' => 'pages', 'action' => 'display', 'home'));

它工作正常,但我不明白 'admin' => true 和 'prefix' => 'admin' 之间的区别是什么。

当我省略时 'prefix' => 'admin' ,路由器不会使用 admin_index而是只使用 index .那么'admin' => true的意义何在? ?

最佳答案

通过设置 'prefix' => 'admin'你告诉 CakePHP 你想使用前缀 admin对于那条路线;基本上意味着您要使用名称以 admin_ 为前缀的 Controller 操作和 View 。 .这部分您已经知道了,仅此而已,事情可能会正常工作。

但是在创建路由时,任何传递给 CakePHP 无法识别的第二个参数的数组键(即不是你通常的 controlleractionpluginprefix 东西)在请求期间被设置为命名参数匹配那条路线。

添加 'admin' => true因此在这种情况下只是一个命名参数,但它有它的优点。首先,它可以使代码更加简洁。

/* Determine if a request came through admin routing */
// without:
if ($this->params['prefix'] == 'admin') {}
// with:
if ($this->params['admin']) {}

/* Create a link that is reverse-routed to an admin prefixed route */
// without:
$html->link('...', array('prefix' => 'admin', 'controller' => 'users'));
// with:
$html->link('...', array('admin' => true, 'controller' => 'users'));

其次,它提供了与 CakePHP 1.2 中管理路由工作方式的向后兼容性(上面示例的最后一行是您在 1.2 中创建管理路由链接的方式)。因此,从 1.2 迁移到 1.3 的开发人员可以通过保留 'admin' => true 来避免更改整个应用程序中的链接。在他们的 route 标记(并添加 'prefix' => 'admin' 一个)。

最后,通过使用命名参数设置像这样的自定义标志并在您的应用程序中使用它而不是通过确切的字符串引用您的路由意味着如果您将前缀更改为其他内容(例如从adminadministratoredit )...虽然这有点有争议,因为您需要重命名所有 admin_* Controller 操作和 View 。 :)

关于cakephp - 路由: 'admin' => true vs 'prefix' => 'admin in CakePHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3152252/

相关文章:

ruby-on-rails - 带有字符串路径的 Redirect_to

php - cakephp3-无法在 Controller 内获取授权 header

php - CakePHP saveAll() 带唯一约束

php - Zend 框架 2 : Catch all route and url escape

Android - 在智能手机和蓝牙模块之间路由音频的功能

c# - 表格没有击中 Controller

c# - WebAPI 路由中的通配符参数不应该匹配

php - 此场景中正确的 mysql 表设计/关系

php - CakePHP 3 - 创建隐藏字段

routing - 在 Azure 上部署时,区域路由在 ASP.NET Core MVC 中不起作用