ZF2如何使用视图助手的JsonModel Ajax调用


ZF2 how to use View Helper for JsonModel Ajax Call

我使用Zend Framework 2。我用AJAX从服务器获得数据,我如何用JSON返回格式化的数据。(例如,多币种格式如. php文件$this->currencyFormat(1234.56, "TRY", "tr_TR"))我不能使用来自操作的视图帮助器。

我的代码像这样。(MyController.php)

<?php
class MyController extends AbstractActionController
{
    public function myAction(){
        $data = array();
        //i want to format this data for multi currency format. as us,fr,tr etc..
        $data['amount'] = '100'; 
        return new JsonModel(data);
    }
}

Yargicx,谢谢你问这个问题。它使我学习了PHP的一个新特性(5.3)。下面是返回原始问题答案的代码:JSON格式的格式化货币。如果您不熟悉可调用类,它可能看起来有点奇怪,但我将解释它是如何工作的。

use Zend'I18n'View'Helper'CurrencyFormat;
use Zend'View'Model'JsonModel;
class MyController extends AbstractActionController
{
    public function myAction()
    {
        $data = array();
        //i want to format this data for multi currency format. as us,fr,tr etc..
        $currencyFormatter = new CurrencyFormat();
        $data['amount'] = $currencyFormatter(1234.56, "TRY", "tr_TR");
        return new JsonModel($data);
    }
}

为了达到这一点,我在Zend'I18n'View'Helper'CurrencyFormat类中查找了currencyFormat()方法,并注意到这是一个受保护的方法,因此我不能直接在控制器动作中使用它。

然后我注意到有一个神奇的__invoke()方法(以前从未见过这个),我在http://www.php.net/manual/en/language.oop5.magic.php#object.invoke上查找了PHP文档。事实证明,您可以像使用下面的函数一样使用对象。注意最后一行:

class Guy
{
    public function __invoke($a, $b)
    {
        return $a + $b;
    }
}
$guy = new Guy();
$result = $guy();

由于Zend'I18n'View'Helper'CurrencyFormat类的__invoke()方法返回调用currencyFormat()方法的结果,因此我们可以使用与currencyFormat()方法相同的参数调用该类,从而在此答案中产生原始代码块。

下面是Zend'I18n'View'Helper'CurrencyFormat类的__invoke()函数的源代码:
public function __invoke(
    $number,
    $currencyCode = null,
    $showDecimals = null,
    $locale       = null,
    $pattern      = null
) {
    if (null === $locale) {
        $locale = $this->getLocale();
    }
    if (null === $currencyCode) {
        $currencyCode = $this->getCurrencyCode();
    }
    if (null === $showDecimals) {
        $showDecimals = $this->shouldShowDecimals();
    }
    if (null === $pattern) {
        $pattern = $this->getCurrencyPattern();
    }
    return $this->formatCurrency($number, $currencyCode, $showDecimals, $locale, $pattern);
}

try

return new JsonModel('data' => $data);

其他都可以

编辑
$jsonencoded = 'Zend'Json'Json::encode($data);//json string
$jsondecode = 'Zend'Json'Json::decode($jsonencoded, 'Zend'Json'Json::TYPE_ARRAY);
http://framework.zend.com/manual/2.0/en/modules/zend.json.objects.html

你是这个意思吗?