Creating helpers

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.

Getting ready

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.

How to do it…

  1. Create the 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, '.', ',');
        }
    }
  2. Add the actionNumbers method to SiteController:
    <?php
    ...
    class SiteController extends Controller
    {
        …
    
        public function actionNumbers()
        {
            return $this->render('numbers', ['value' => 18878334526.3]);
        }
    }
  3. Add the 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>
  4. Open the action. You should see the following result:
    How to do it…

In other cases, you can specify another count of decimal numbers. Observe the following example:

NumberHelper::format($value, 3)

How it works…

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.

Note

Usually, static helpers are lightweight clean functions with a small count of arguments. Avoid putting your business logic and other complicated manipulations into helpers. Use widgets or other components instead of helpers in other cases.

See also

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.245.196