I am looking to load values from my database in my /app/Config/routes.php configuration file.
At the top I am using: App::uses('Option', 'Model');
And I am calling my find in my class: $this->Option->find('all');
Am I missing something?
I am looking to load values from my database in my /app/Config/routes.php configuration file.
At the top I am using: App::uses('Option', 'Model');
And I am calling my find in my class: $this->Option->find('all');
Am I missing something?
I think you have to instantiate the model before you use it:
App::uses('Option', 'Model');
$option = new Option();
$something = $option->find('all');
I wouldn't put any database queries in Routes. It's not the place for them (separation of concerns etc). It will also slow down every request and the routes shouldn't be changing all that frequently.
What I've done is to create a routes file in app/tmp/cache every time a database route is created/updated (your code will be different but this is how I do it).
In your route model:
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);
}
Call rebuildCache() from your route model afterSave():
function afterSave() {
$this->rebuildCache();
}
Simply include the file in Routes.php:
$routes_cache_filename = TMP . 'cache' . DS . 'routes.php';
if (file_exists($routes_cache_filename)) {
require_once $routes_cache_filename;
}
/*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']));
}