我有一些我想重构的示例代码,因为我需要它在保存记录后才能工作。它目前在首次渲染记录后使用(使用afterFilter)。它的作用是使用布局渲染我想要的视图并将其保存到文件中。
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 :(得分:2)
您可以考虑在模型中的afterSave()中设置成员变量,并在控制器中的afterFilter()中检查该值。
答案 1 :(得分:0)
我在搜索如何从模型中渲染视图时找到了这个线程。在我的情况下,我在模型中调用自定义方法,因此这可能不适用于afterSave(),但如果您调用自定义方法,则可以这样做:
控制器:
$this->Model->myFunc($this);
模型
public function myFunc($object) {
$object->render();
}
希望能帮助遇到此线索的其他人。