【发布时间】:2015-01-06 18:40:47
【问题描述】:
我遇到了一个问题,我确信这只是因为我对蛋糕生锈了。我正在尝试创建一个默认或包罗万象的路由,只有在所有其他路由都失败时才会匹配。根据我对大多数 MVC 框架的理解,我假设以下内容就足够了:
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
#... other routes
Router::connect('/*', array('controller' => 'pages', 'action' => 'dynamic_display', 'home'));
CakePlugin::routes();
require CAKE . 'Config' . DS . 'routes.php';
这样做的问题是Router::connect('/*') 路由会导致与之前的路由发生冲突。我也尝试过“slug”路线,但我对冲突有同样的问题。
是否有任何解决此问题的方法或可能的解决方法?
提前致谢。
编辑
在下面的评论中,我链接到了一条评论,该评论为我的问题提供了一个不错的解决方案。这是我的简单概念证明。
页面.php
<?php
App::uses('AppModel', 'Model');
/**
* Page model
* @uses AppModel
*/
class Page extends AppModel {
/**
* MongoDB Schema definitions
*
* @var array 'mongoSchema'
* @link https://github.com/ichikaway/cakephp-mongodb/
*/
var $mongoSchema = array(
'title'=>array('type'=>'string'),
'meta_description'=>array('type'=>'text'),
'slug'=>array('type'=>'string'),
'content'=>array('type'=>'text'),
'published'=>array('type'=>'bool'),
'created'=>array('type'=>'datetime'),
);
/**
* afterSave method.
* @return void
*/
public function afterSave($created, $options=array()) {
$this->__rebuildRouteCache();
}
/**
* rebuild route cache method. This will rewrite the routes for our simple CMS each time a page is added or updated
* @return void
*/
private function __rebuildRouteCache() {
$pages = $this->find('all');
$filename = TMP . 'cache' . DS . 'routes.php';
$buffer = "<?php \r\n";
foreach($pages as $page) {
$buffer .= 'Router::connect("'. $page['Page']['slug'] .'", array( "controller" => "pages", "action" => "dynamic_display"));';
$buffer .= "\r\n";
}
$buffer .= "?>";
file_put_contents($filename, $buffer);
}
}
?>
routes.php
<?php
#..snip
/**
* Include our route cache if it exists
*/
$fname = TMP . 'cache' . DS . 'routes.php';
if(file_exists($fname)) {
require_once $fname;
}
/**
* Load all plugin routes. See the CakePlugin documentation on
* how to customize the loading of plugin routes.
*/
CakePlugin::routes();
/**
* Load the CakePHP default routes. Only remove this if you do not want to use
* the built-in default routes.
*/
require CAKE . 'Config' . DS . 'routes.php';
?>
这不是我想要的包罗万象的路线,但它是适合我情况的可行解决方案。希望这对其他人也有用。
【问题讨论】:
-
This comment 为我的问题提供了一个很好的解决方案。每次添加动态页面或更改 slug 时,我都可以编写新的 routes.php。