嗨,我正在 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 无法识别的第二个参数的数组键(即不是你通常的 controller
、 action
、 plugin
、 prefix
东西)在请求期间被设置为命名参数匹配那条路线。
添加 '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'
一个)。最后,通过使用命名参数设置像这样的自定义标志并在您的应用程序中使用它而不是通过确切的字符串引用您的路由意味着如果您将前缀更改为其他内容(例如从
admin
到 administrator
或 edit
)...虽然这有点有争议,因为您需要重命名所有 admin_*
Controller 操作和 View 。 :)
关于cakephp - 路由: 'admin' => true vs 'prefix' => 'admin in CakePHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3152252/