在CakePHP中可以使用Model :: afterSave()中的Controller :: render()吗?

问题描述:

我有一些示例代码,我想重构,因为我需要它保存记录后工作。它目前在记录第一次渲染后使用(使用afterFilter)。它所做的是呈现我想要的布局并将其保存到文件中的视图。在CakePHP中可以使用Model :: afterSave()中的Controller :: render()吗?

function afterFilter() { 
    parent::afterFilter(); 
    if($this->params['pass'][0] == 'contact') { 
     $surrenderOuput = $this->surrender($this->params['pass'][0]); 
     $path = WWW_ROOT . 'cache' . DS . $this->params['pass'][0] . DS . 'index.html'; 
     $file = new File($path, true); 
     $file->write($surrenderOuput); 
     $file->close(); 
    } 
} 
function surrender($action = null, $layout = null, $file = null) { 
    $this->beforeRender(); 

    $viewClass = $this->view; 
    if ($this->view != 'View') { 
     if (strpos($viewClass, '.') !== false) { 
      list($plugin, $viewClass) = explode('.', $viewClass); 
     } 
     $viewClass = $viewClass . 'View'; 
     App::import('View', $this->view); 
    } 

    $this->Component->beforeRender($this); 

    $this->params['models'] = $this->modelNames; 

    if (Configure::read() > 2) { 
     $this->set('cakeDebug', $this); 
    } 

    $View =& new $viewClass($this); 

    if (!empty($this->modelNames)) { 
     $models = array(); 
     foreach ($this->modelNames as $currentModel) { 
      if (isset($this->$currentModel) && is_a($this->$currentModel, 'Model')) { 
       $models[] = Inflector::underscore($currentModel); 
      } 
      $isValidModel = (
       isset($this->$currentModel) && is_a($this->$currentModel, 'Model') && 
       !empty($this->$currentModel->validationErrors) 
      ); 
      if ($isValidModel) { 
       $View->validationErrors[Inflector::camelize($currentModel)] =& 
        $this->$currentModel->validationErrors; 
      } 
     } 
     $models = array_diff(ClassRegistry::keys(), $models); 
     foreach ($models as $currentModel) { 
      if (ClassRegistry::isKeySet($currentModel)) { 
       $currentObject =& ClassRegistry::getObject($currentModel); 
       if (is_a($currentObject, 'Model') && !empty($currentObject->validationErrors)) { 
        $View->validationErrors[Inflector::camelize($currentModel)] =& 
         $currentObject->validationErrors; 
       } 
      } 
     } 
    } 

    $this->autoRender = false; 
    $output = $View->render($action, $layout, $file); 

    return $output; 
} 

所以我基本上呈现视图与它的布局,并返回它作为输出,并将其保存到一个文件中。大。有没有什么办法在模型中做类似的事情?

+0

我确定有一些方法可以将它们一起使用,但这会严重违反MVC结构,几乎肯定会产生副作用。每次保存记录时,为什么要渲染某个视图? – deceze 2009-08-10 04:59:07

+0

为了将该视图缓存为文件。就mysql而言,主机(Godaddy)的性能非常糟糕。 – 2009-08-12 22:28:40

您可以考虑在模型中的afterSave()中设置一个成员变量,并在控制器的afterFilter()中检查该值。

+0

我最终做了一个使用Model :: afterSave()的行为。花了一段时间弄清楚如何做,但使用Controller :: render()不是这样。 Controller :: requestAction(),并传递一个param,自动呈现beforeFilter中检查的布局,似乎解决了我的问题。谢谢 :) – 2009-08-12 22:30:41

我在搜索如何渲染模型视图时发现此线程。在我的情况我打电话模型中的一个自定义的方法,所以这可能不是afterSave()工作,但如果你调用一个自定义的方法,你可以做这样的:

控制器:

$this->Model->myFunc($this); 

型号

public function myFunc($object) { 
$object->render(); 
} 

希望帮助别人谁碰到这个线程来。