Using Model in routes file, cakephp

拟墨画扇 提交于 2019-11-29 23:35:34

问题


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?


回答1:


I think you have to instantiate the model before you use it:

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



回答2:


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;

}



回答3:


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


来源:https://stackoverflow.com/questions/12310953/using-model-in-routes-file-cakephp

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