【发布时间】:2012-09-07 02:31:38
【问题描述】:
我希望在 /app/Config/routes.php 配置文件中从我的数据库中加载值。
在我使用的顶部:App::uses('Option', 'Model');
我在课堂上打电话给我的发现:$this->Option->find('all');
我错过了什么吗?
【问题讨论】:
标签: cakephp cakephp-2.2
我希望在 /app/Config/routes.php 配置文件中从我的数据库中加载值。
在我使用的顶部:App::uses('Option', 'Model');
我在课堂上打电话给我的发现:$this->Option->find('all');
我错过了什么吗?
【问题讨论】:
标签: cakephp cakephp-2.2
我不会在 Routes 中放置任何数据库查询。这不是他们的地方(关注点分离等)。它还会减慢每个请求,并且路由不应该经常更改。
我所做的是每次创建/更新数据库路由时在 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);
}
在你的路由模型 afterSave() 调用rebuildCache():
function afterSave() {
$this->rebuildCache();
}
只需将文件包含在 Routes.php 中:
$routes_cache_filename = TMP . 'cache' . DS . 'routes.php';
if (file_exists($routes_cache_filename)) {
require_once $routes_cache_filename;
}
【讨论】:
我认为您必须在使用模型之前对其进行实例化:
App::uses('Option', 'Model');
$option = new Option();
$something = $option->find('all');
【讨论】:
Cannot redeclare class DATABASE_CONFIG 错误
routes.php的database.php?这可能会导致您看到的错误(因为该类是在 database.php 中声明的)。
$this。
/*Load ClassRegistry*/
App::uses('ClassRegistry', 'Utility');
/**
* Initialize model and perform find
*/
$Cms = ClassRegistry::init('Cms');
$cmsdata = $Cms->find('all');
/**
* Iterate over results and define routes
*/
foreach ($cmsdata as $cmsrow) {
Router::connect('/', array('controller' => $cmsrow['Cms']['controller'], 'action' => $cmsrow['Cms']['slug']));
}
【讨论】: