There are a lot of built-in framework helpers such as StringHelper
in the yiihelpers
namespace. These contain sets of helpful static methods for manipulating strings, files, arrays, and other subjects.
In many cases, for additional behavior you can create a own helper and put any static function into one. For example, we implement the number helper in this recipe.
Create a new yii2-app-basic
application using the composer package manager as described in the official guide at http://www.yiiframework.com/doc-2.0/guide-start-installation.html.
helpers
directory in your project and write the NumberHelper
class:<?php namespace apphelpers; class NumberHelper { public static function format($value, $decimal = 2) { return number_format($value, $decimal, '.', ','); } }
actionNumbers
method to SiteController
:<?php ... class SiteController extends Controller { … public function actionNumbers() { return $this->render('numbers', ['value' => 18878334526.3]); } }
views/site/numbers.php
view:<?php use apphelpersNumberHelper; use yiihelpersHtml; /* @var $this yiiwebView */ /* @var $value float */ $this->title = 'Numbers'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="site-numbers"> <h1><?= Html::encode($this->title) ?></h1> <p> Raw number:<br /> <b><?= $value ?></b> </p> <p> Formatted number:<br /> <b><?= NumberHelper::format($value) ?></b> </p> </div>
In other cases, you can specify another count of decimal numbers. Observe the following example:
NumberHelper::format($value, 3)
Any helper in Yii2 is just a set of functions, implemented as static methods in the corresponding classes.
You can use a helper for implementing any different formats of output, for manipulations with values of any variables, and for other cases.
For more information about helpers, refer to:
http://www.yiiframework.com/doc-2.0/guide-helper-overview.html.
For examples of built-in helpers, refer to sources in the helpers
directory of framework. For the framework, refer to:
https://github.com/yiisoft/yii2/tree/master/framework/helpers.
18.221.245.196