2

我开发了一个代码,其中包含一个以 json 格式返回产品评级的查询。代码如下:

<?php header('content-type: application/json; charset=utf-8');
require_once('/opt/phpapps/magento/app/Mage.php');
umask(0);
Mage::app();
$cid=$_GET['catid'];
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$query = "SELECT round(t1.rating_summary / 20) AS rating, t2.product_id FROM review_entity_summary AS t1 INNER JOIN catalog_category_product AS t2 ON t1.entity_pk_value = t2.product_id WHERE category_id =" . $cid . " AND store_id = '1'";

$results = $read->fetchAll($query);
$json = json_encode($results);
print_r( $json );
?>

我被指示将其转换为 MVC 模式。我知道 MVC 可以通过创建单独的文件夹来完成,如块、控制器、模型、sql 等,帮助文件夹。但我不确定下一步是什么以及如何执行开发以获取 json 数据..帮助我...

4

1 回答 1

1

最好的方法是创建一个自定义扩展/模型,有很多教程可以做到这一点,但是你可以使用一些东西来生成一个例子让你开始:

http://www.silksoftware.com/magento-module-creator/

但是,对于这么简单的事情,您可以在本地命名空间中创建一个自定义块,例如:

app/code/local/Mage/Catalog/Block/Product/Ratingsjson.php

<?php
/**
 * Ratingsjson.php
 */
class Mage_Catalog_Block_Product_Ratingsjson extends Mage_Catalog_Block_Product_Abstract
{
    /**
     * Get products with special offer attribute set
     * 
     * @return type
     */
    public function getRatings() 
    { 
        /**
         * This will be injected from the tag / XML below
         * you can pass what ever variables you want this way.
         * getSomeAttribute() will get the value 'some_attribute' from the
         * CMS tag or XML config.
         */
        $categoryId = $this->getCategoryId();
        if($categoryId == NULL) {
             $categoryId = 1; // or some default;
        }

        $resource = Mage::getSingleton('core/resource');
        $read = $resource->getConnection('catalog_read');

        // Do your stuff here...
        $query = "SELECT round(t1.rating_summary / 20) AS rating, t2.product_id FROM review_entity_summary AS t1 INNER JOIN catalog_category_product AS t2 ON t1.entity_pk_value = t2.product_id WHERE category_id =" . $cid . " AND store_id = '1'";
        $results = $read->fetchAll($query);

        return json_encode($results);
    }
}

创建一个模板来做你想做的事:

模板/mymodeule/mytemplate.phtml

<?php
echo $this->getRatings();

然后,您可以在 CMS 页面中使用您的新块:

{{block type="catalog/ratignsjson" category_id="3" temaplte="mymodeule/mytemplate.phtml"}}

或者,如果您想通过 XML 配置加载它:

<block type="catalog/ratignsjson" category_id="3" name="ratignsjson" template="mymodeule/mytemplate.phtml"/> 

要正确执行此操作并输出严格的 Json 数据,您需要设置 json 内容类型标头等,但我认为这对于这种特殊情况来说有点太多了。

于 2013-02-15T11:28:39.033 回答