ala*_*ock 3 cakephp cakephp-2.2
我期待在我的/app/Config/routes.php配置文件中加载我的数据库中的值.
在顶部,我正在使用: App::uses('Option', 'Model');
我在课堂上称呼我的发现: $this->Option->find('all');
我错过了什么吗?
我不会在路由中放置任何数据库查询.它不是他们的地方(关注点分离等).它也会减慢每个请求,并且路由不应该经常更改.
我所做的是每次创建/更新数据库路由时在app/tmp/cache中创建一个路由文件(你的代码会有所不同,但这就是我的工作方式).
在您的路线模型中:
function rebuildCache() {
$data = $this->find('all');
$buffer = "<?php\n";
$filename = TMP . 'cache' . DS . 'routes.php';
foreach($data as $item) {
$url = Router::parse('/' . $item['Route']['destination']);
if (count($url['pass']) > 0) {
$id = $url['pass'][count($url['pass']) - 1];
}
else {
$id = null;
}
$buffer .= "Router::connect('/{$item['Route']['url']}', array('controller'=>'{$url['controller']}', 'action'=>'{$url['action']}', {$id}));\n";
}
file_put_contents($filename, $buffer);
}
Run Code Online (Sandbox Code Playgroud)
从您的路径模型afterSave()调用rebuildCache():
function afterSave() {
$this->rebuildCache();
}
Run Code Online (Sandbox Code Playgroud)
只需在Routes.php中包含该文件:
$routes_cache_filename = TMP . 'cache' . DS . 'routes.php';
if (file_exists($routes_cache_filename)) {
require_once $routes_cache_filename;
}
Run Code Online (Sandbox Code Playgroud)