Using Model in routes file, cakephp

2019-02-11 01:16发布

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?

3条回答
在下西门庆
2楼-- · 2019-02-11 01:59

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楼-- · 2019-02-11 02:03
  /*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']));
  }
查看更多
小情绪 Triste *
4楼-- · 2019-02-11 02:11

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

App::uses('Option', 'Model');
$option = new Option();
$something = $option->find('all');
查看更多
登录 后发表回答