php - ZF2 how to use View Helper for JsonModel Ajax Call -


i use zend framework 2. data server ajax , how can return formatted data json. (for example multi currency format in .phtml file $this->currencyformat(1234.56, "try", "tr_tr")) cannot use view helper action.

my code this. (mycontroller.php)

<?php class mycontroller extends abstractactioncontroller {     public function myaction(){         $data = array();         //i want format data multi currency format. us,fr,tr etc..         $data['amount'] = '100';           return new jsonmodel(data);     }  } 

yargicx, asking question. caused me learn new feature of php (5.3). here code returns answer original question: formatted currency in json. may little weird if aren't familiar invokable classes, i'll explain how works.

use zend\i18n\view\helper\currencyformat; use zend\view\model\jsonmodel;  class mycontroller extends abstractactioncontroller {     public function myaction()     {         $data = array();         //i want format data multi currency format. us,fr,tr etc..         $currencyformatter = new currencyformat();         $data['amount'] = $currencyformatter(1234.56, "try", "tr_tr");          return new jsonmodel($data);     } } 

to point, looked currencyformat() method in zend\i18n\view\helper\currencyformat class , noticed protected method, couldn't use directly in controller action.

i noticed there magic __invoke() method , (having never seen before) looked php documentation @ http://www.php.net/manual/en/language.oop5.magic.php#object.invoke. turns out, can use object if function following. note last line:

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

since __invoke() method of zend\i18n\view\helper\currencyformat class returns result of call currencyformat() method, can invoke class same parameters currencyformat() method, resulting in original codeblock in answer.

for kicks, here source code of __invoke() function of zend\i18n\view\helper\currencyformat class:

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); } 

Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -