我不想在此頁面中硬編碼值,而是想從數據庫中提取值並設置主頁面。修改cakephp中的Routes.php文件
Router::connect('/', array('controller' => 'tools', 'action' => 'index'));
而是控制器和行動的硬編碼值,我想火上PostgreSQL數據庫的查詢,並把這些值連接語句。但我無法在routes.php文件中啓動查詢。
我不想在此頁面中硬編碼值,而是想從數據庫中提取值並設置主頁面。修改cakephp中的Routes.php文件
Router::connect('/', array('controller' => 'tools', 'action' => 'index'));
而是控制器和行動的硬編碼值,我想火上PostgreSQL數據庫的查詢,並把這些值連接語句。但我無法在routes.php文件中啓動查詢。
您可以在routes.php文件定義動態路由,像這樣:
/**
* Initialize model and perform find
*/
$Route = ClassRegistry::init('Route');
$routes = $Route->find('all');
/**
* Iterate over results and define routes
*/
foreach ($routes as $route) {
Router::connect('/', array('controller' => $route['Route']['controller'], 'action' => $route['Route']['action']));
}
在這個例子中,我使用了路線模型來創建我的路線。實際上,這可能是您選擇的任何模型。
一種替代,是插到你的路由型號afterSave()回調,並生成路由的高速緩存版本,像(CakePHP2.0):
class Route extends AppModel {
public function rebuildRouteCache() {
$routes = $this->find('all')
$routeCache = new File(CACHE . 'route_cache.php', true);
$routeCache->write('<?php' . "\n");
foreach($routes as $route) {
$parsed = Router::parse($route['Route']['url']);
$routeCache->write("Router::connect('" . $route['Route']['route'] . "', array('controller'=>'" . $parsed['controller'] . "', 'action'=>'" . $parsed['action'] . "', '" . $parsed['pass'][0] . "', 'plugin'=>'" . $parsed['plugin'] . "'));\n");
}
$routeCache->close();
return true;
}
public function afterSave($created) {
$this->rebuildRouteCache();
return true;
}
}
,並添加以下到應用程序/配置/routes.php:
if (file_exists(CACHE . "route_cache.php")) {
require CACHE . 'route_cache.php';
}
這樣,當一個路徑保存在routes_cache.php文件將只更新,你不會有負載的額外開銷和閱讀的每一個頁面請求路由表。
謝謝,你的代碼實際上解釋瞭如何比文檔更好地使用Cake的文件功能。 – AngeloS
順便說一句,我的答案中的例子會發送我所有的動態路由到根網址。這純粹是向你展示如何使用查找結果。 –
你在哪個文件夾中放置了Route模型? – user299128
所有模型應該位於應用/模型/文件夾中。 –