2012-09-07 38 views
3

我期待在我/app/Config/routes.php配置文件從我的數據庫加載值。使用模式,CakePHP的

在我使用的頂部:App::uses('Option', 'Model');

我打電話來我發現在我的課:$this->Option->find('all');

我缺少的東西?

回答

2

認爲你在使用它之前實例化模型:

App::uses('Option', 'Model'); 
$option = new Option(); 
$something = $option->find('all'); 
+0

格拉西亞斯。似乎讓我更接近。我沒有收到關於我的遺失物品的錯誤。但我得到一個'無法重新聲明類DATABASE_CONFIG \t'錯誤 – alairock

+0

奇怪,我剛查了,我已經使用正是上一個項目,它的工作。你是否有機會從'routes.php'中包含'database.php'?這可能會導致你看到的錯誤(因爲該類聲明在database.php)。 – bfavaretto

+0

@alairock其實,我剛剛更新了我的回答什麼,我對我的項目中使用的等同。儘量不要使用'$ this'。 – bfavaretto

5

我不會把任何數據庫查詢的路線。這不是他們的地方(關注點分離等)。它也會減慢每個請求的速度,路由不應該頻繁地改變。

我所做的就是每次創建數據庫路徑時創建的應用程序的/ tmp /緩存中的文件路徑/更新的(你的代碼會有所不同,但是這是我如何做到這一點)。

在路線模式:

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); 

} 

呼叫rebuildCache()從你的路徑模型,afterSave():

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; 

} 
+0

如何調用afterSave函數表單Config/routes.php – GYaN

0
/*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'])); 
    }