【问题标题】:Using Model in routes file, cakephp在路由文件中使用模型 cakephp
【发布时间】:2012-09-07 02:31:38
【问题描述】:

我希望在 /app/Config/routes.php 配置文件中从我的数据库中加载值。

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

我在课堂上打电话给我的发现:$this->Option->find('all');

我错过了什么吗?

【问题讨论】:

    标签: cakephp cakephp-2.2


    【解决方案1】:

    我不会在 Routes 中放置任何数据库查询。这不是他们的地方(关注点分离等)。它还会减慢每个请求,并且路由不应该经常更改。

    我所做的是每次创建/更新数据库路由时在 app/tmp/cache 中创建一个路由文件(您的代码会有所不同,但我就是这样做的)。

    在您的路线模型中:

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

    在你的路由模型 afterSave() 调用rebuildCache():

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

    【讨论】:

    • 我如何在 Config/routes.php 中调用 afterSave 函数
    【解决方案2】:

    认为您必须在使用模型之前对其进行实例化:

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

    【讨论】:

    • 谢谢。似乎让我更接近。我没有收到关于我丢失的对象的错误。但我确实收到了 Cannot redeclare class DATABASE_CONFIG 错误
    • 奇怪,我刚刚检查过,我已经在一个项目中完全使用了它,它确实有效。你有没有机会包括来自routes.phpdatabase.php?这可能会导致您看到的错误(因为该类是在 database.php 中声明的)。
    • @alairock 实际上,我刚刚将我的答案更新为我在项目中使用的答案。尽量不要使用$this
    • 宾果游戏。 App::uses('选项', '模型');已经包含一个 include 没有意识到,我实际上确实将它再次包含在我的路由文件中,在我需要加载模型之前这不是问题。谢谢!
    • 我们如何在 cakephp 3.6 中做到这一点?
    【解决方案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']));
      }
    

    【讨论】:

      猜你喜欢
      • 2011-10-22
      • 2012-04-04
      • 2012-11-01
      • 2014-01-03
      • 2012-12-03
      • 2012-08-23
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多