深入理解Magento – 第三章 – Magento的布局(Layout),块(Block)和模板(Template)
我们接着研究Magento。根据我们第二章讲的Magento MVC的架构,我们接下来应该讲模型(Model),但是我们跳过模型先来看布局和块。和一些流行的PHP MVC架构不同的是,Magento的执行控制器不直接将数据传给试图,相反的视图将直接引用模型,从模型取数据。这样的设计就导致了视图被拆分成两部分,块(Block)和模板(Template)。块是PHP对象,而模板是原始PHP文件,混合了XHTML和PHP代码(也就是把PHP作为模板语言来使用了)。每一个块都和一个唯一的模板文件绑定。在模板文件phtml中,“$this”就是指该模板文件对应的快对象。
让我们来看一个例子
File: app/design/frontend/base/default/template/catalog/product/list.phtml
你将看到如下代码
< ?php $_productCollection=$this->getLoadedProductCollection() ?> < ?php if(!$_productCollection->count()): ?> <p class="note-msg">< ?php echo $this->__('There are no products matching the selection.') ?></p> < ?php else: ?>
这里“getLoadedProductCollection”方法可以在这个模板的块对象“Mage_Catalog_Block_Product_List”中找到
File: app/code/core/Mage/Catalog/Block/Product/List.php ... public function getLoadedProductCollection() { return $this->_getProductCollection(); } ...
块的“_getProductCollection”方法会实例化模型,并读取数据然后返回给模板。


