Using Model in routes file, cakephp

允我心安 提交于 2019-11-30 15:48:31

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']));
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!