几年前我正在使用PHP,我非常了解OOP,但我是Zend Framework 2的新手,我的概念遇到了一些麻烦。
我正在尝试开发一个已经完成的网站,但现在已经使用ZF2了。
我最大的问题之一是布局/视图(我已经知道它们之间的区别)。
在该网站中,有一个动态生成的侧边栏菜单(从DB中提取的内容......让我们在CategoriesController中调用sideBarGenAction)。我需要在每个页面(布局模板内)中显示它。所以,这是我的疑惑:如何做到这一点,而不是在每个其他Action中调用Action(sideBarGenAction)?
如果侧边栏有静态内容,我可以使用$ this-> partial,但它有动态内容,部分需要变量传递给。
我想我可以创建一个ViewHelper,但它没有多大意义(因为它不是Widget,它是Model中的业务规则....如果我必须创建一个ViewHelper,我会做的一切需要在视图中“调用”,我不需要MVC框架。)
答案 0 :(得分:3)
因此,您的模型应该具有可重复使用的单元可测试方法来捕获数据,可以是字符串,对象,数组等。这是正确处理数据的逻辑,因此它可以以一种有意义的方式使用,并且可以进行单元测试。
在控制器中,您实例化该模型的实例并使用获取要使用的数据所需的方法。然后将其传递给视图。现在这可以在动作本身中,或者,您可以创建一个可重用的方法来执行此操作并返回数据,以便其他操作也可以使用它。如果这也是可以在其他控制器中使用的东西,那么你应该创建一个控制器使用的动作帮助器....你明白了......有很多方法可以构建相同的东西,具体取决于你对重用代码的关注程度如何。
要将数据从控制器传递到zf1中的视图,您需要像这样执行
$this->view->whateverItIsCalled = $someValueOrArrayTypeThing;
然后在视图中使用它,回复它等,如$this->whateverItIsCalled.
在zf2中,就像这样
namespace Content\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class ArticleController extends AbstractActionController
{
public function viewAction()
{
// get the article from the persistence layer, etc...
$view = new ViewModel();
$articleView = new ViewModel(array('article' => $article));
$articleView->setTemplate('content/article');
$primarySidebarView = new ViewModel();
$primarySidebarView->setTemplate('content/main-sidebar');
$secondarySidebarView = new ViewModel();
$secondarySidebarView->setTemplate('content/secondary-sidebar');
$sidebarBlockView = new ViewModel();
$sidebarBlockView->setTemplate('content/block');
$secondarySidebarView->addChild($sidebarBlockView, 'block');
$view->addChild($articleView, 'article')
->addChild($primarySidebarView, 'sidebar_primary')
->addChild($secondarySidebarView, 'sidebar_secondary');
return $view;
}
}
并且视图将像在zf1中使用之前的内容一样使用它,例如
<?php // "content/article" template ?>
<div class="row content">
<?php echo $this->article ?>
<?php echo $this->sidebar_primary ?>
<?php echo $this->sidebar_secondary ?>
</div>
<?php // "content/article" template ?>
<!-- This is from the $articleView View Model, and the "content/article"
template -->
<article class="span8">
<?php echo $this->escapeHtml('article') ?>
</article>
<?php // "content/main-sidebar" template ?>
<!-- This is from the $primarySidebarView View Model, and the
"content/main-sidebar" template -->
<div class="span2 sidebar">
sidebar content...
</div>
<?php // "content/secondary-sidebar template ?>
<!-- This is from the $secondarySidebarView View Model, and the
"content/secondary-sidebar" template -->
<div class="span2 sidebar pull-right">
<?php echo $this->block ?>
</div>
<?php // "content/block template ?>
<!-- This is from the $sidebarBlockView View Model, and the
"content/block" template -->
<div class="block">
block content...
</div>
您可以看到如何实例化新的视图模型,然后不仅将事物传递给视图,还可以指定更具体的部分,这是不同的。
无论如何,希望能帮到你。基本上,长话短说,ZF2由于一些原因提高了ZF1的性能,但减少开销是一个重要的原因。事实上,大多数框架都是这样做的,因为在需要时你只需要你需要的东西。