How to create a new helper in Yii2 framework:
Create a new file “Utils.php” in “app-basic\helpers” or in other folder, location is up to you, but keep things organized!
<?php namespace yii\helpers; use Yii; class Utils { public static function pre($mixed_data) { print '<pre style="white-space: pre-wrap; white-space: -moz-pre-wrap; white-space: -o-pre-wrap; background: #faf8f0; border: 1px solid silver; padding: 2px; font-weight: normal; font-family: Monospace, Courier">'; print_r($mixed_data); print '</pre>'; } public static function code($mixed_data) { print '<code style=" display: block; padding: 0.5em 1em; border: 1px solid #bebab0;">'; print_r($mixed_data); print '</code>'; } }
In this helper we have 2 functions to display raw data.
Include this file in your entry script app-basic/web/index.php;
require(__DIR__ . '/../vendor/autoload.php'); require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php'); require(__DIR__ . '/../helpers/utils.php');
Use these helpers in your view files:
<?php Utils::pre(array("test"=>"array data", "boo"=>"echo"));?> <?php Utils::code(array("test"=>"test data", "boo"=>"echo"));?>
Yii2: create helper