If you're asking, "What's Yii?" check out Introduction to the Yii Framework, which reviews the benefits of Yii and includes an overview of Yii 2.0.
What Are Helpers?
In the Programming With Yii2 series, I'm guiding readers in use of the Yii2 Framework for PHP. In this tutorial, I'll provide a brief overview of helpers. In Yii, helpers are modules which group commonly useful libraries for string, file, image, URL and HTML management amongst other things, and they are easy to extend.
I'll also share an example of creating a helper within Meeting Planner, the focus of our Envato Tuts+ startup series.
Before we get started, please remember, I do try to participate in the discussions below. If you have a question or topic suggestion, please post a comment below or contact me on Twitter @reifman.
If you noticed the gap in between the Programming Yii series episodes, it's because I had to have brain surgery last year. Thank you for your patience and support—it's nice to be writing again regularly, and I'm looking forward to continuing coverage of Yii2.
Yii2 Helper Libraries
Essentially, helpers are just modules of topically oriented coding support. Here's a list of helpers provided as part of Yii2—this list is now a bit more up to date than the documentation and its menus:
- ArrayHelper simplifies array handling with functions such as safely looking up values, mapping, merging, etc.
- Console assists with command-line functionality, gathering input and outputting colored text.
- FileHelper extends basic PHP file management features.
- FormatConverter converts different formats, mostly dates for now.
- Html programmatically generates commonly used HTML tags.
- HtmlPurifier cleanses input text from users to improve security.
- Imagine provides image manipulation features provided by the yii2-imagine extension.
- Inflector provides useful string functions for common transformations.
- Json encodes and decodes JSON data.
- Markdown converts markdown into HTML.
- StringHelper extends the basic PHP functions for strings.
- Url assists with programmatically creating URLs and remembering them for navigation.
- VarDumper provides an advanced var_dump feature.
I commonly use the Html and Url helpers across my Yii applications. And, you may remember, I used the Imagine helper in Building Your Startup With PHP: User Settings, Profile Images and Contact Details to scale uploaded profile images.
Let's take a brief look at some of the less commonly known helpers.
ArrayHelper
As you can see, ArrayHelper provides a handful of useful array-oriented functions.
For example, getValue simplifies looking up values from keys in complex arrays:
// working with array $username = \yii\helpers\ArrayHelper::getValue($_POST, 'username'); // working with object $username = \yii\helpers\ArrayHelper::getValue($user, 'username'); // working with anonymous function $fullName = \yii\helpers\ArrayHelper::getValue($user, function ($user, $defaultValue) { return $user->firstName . ' ' . $user->lastName; }); // using dot format to retrieve the property of embedded object $street = \yii\helpers\ArrayHelper::getValue($users, 'address.street'); // using an array of keys to retrieve the value $value = \yii\helpers\ArrayHelper::getValue($versions, ['1.0', 'date']);
Or map() builds a simple key value array from a more complex array:
$array = [ ['id' => '123', 'name' => 'aaa', 'class' => 'x'], ['id' => '124', 'name' => 'bbb', 'class' => 'x'], ['id' => '345', 'name' => 'ccc', 'class' => 'y'], ]; $result = ArrayHelper::map($array, 'id', 'name'); // the result is: // [ // '123' => 'aaa', // '124' => 'bbb', // '345' => 'ccc', // ]
HtmlPurifier
You can use HtmlPurifier to improve the security of handling with user input. For example, if someone pastes SQL injection code into your form as above, cleansing it with HtmlPurifier will neutralize any attack.
echo HtmlPurifier::process($html);
It leverages the open-source HTML Purifier library.
StringHelper
StringHelper provides some extended methods for working with strings in PHP. For example, truncateWords() can reduce a string to a certain number of words but also preserve proper HTML within the result.
Building Your Own Helper
As Meeting Planner, the focus of the startup series, got bigger, I found it helpful to create a basic helper that I could use. For now, I combined everything into one called MiscHelpers.php:
<?php namespace common\components; use yii; use yii\helpers\Url; use common\models\User; class MiscHelpers { public static function buildCommand($meeting_id,$cmd=0,$obj_id=0,$actor_id=0,$auth_key='') ... public static function backendBuildCommand($meeting_id,$cmd=0,$obj_id=0,$actor_id=0,$auth_key='') ... public static function isProfileEmpty($user_id) ... public static function getDisplayName($user_id,$no_email=false) ... public static function getTimezoneList() ... public static function fetchUserTimezone($user_id) ... public static function getUrlPrefix() ... }
You can see a variety of methods are included of different types. For example, getDisplayName()
returns either a username, an email, or concatenated strings of first and last name when available.
It's helpful to create these once in a single place rather than rewrite them differently in models as they are needed.
I created MiscHelpers.php by creating a file in /common/components and building a class which I could invoke throughout the application.
The buildCommand
function makes it easy to programmatically build links for outbound email messages which include the ability to authenticate users with the $auth_key
stored in the database.
public static function buildCommand($meeting_id,$cmd=0,$obj_id=0,$actor_id=0,$auth_key='') { // to do - build string of local or remote destination // note: if change made, change in Message.php return Url::to(['meeting/command','id'=>$meeting_id,'cmd'=>$cmd,'actor_id'=>$actor_id,'k'=>$auth_key,'obj_id'=>$obj_id,],true); }
There's not really anything special about this module other than that it resembles the goal of standard Yii Helpers which I described earlier.
Anywhere I want to use MiscHelper functions, I can use the following code:
<?php use common\components\MiscHelpers; ... <tr> <td style="color:#777; font-family:Helvetica, Arial, sans-serif; ... Hi <?php echo Html::encode(MiscHelpers::getDisplayName($user_id)); ?>,
As Meeting Planner grows, I'll probably create a variety of helpers more traditionally organized around topical issues.
In Closing
Yii Helpers are as they are named, helpful. And, as busy coders, we may not be aware they exist. I hope you saw some helper functions within the Yii modules above that will prove useful to you over time. And I hope the Yii team keeps expanding on them with each update.
I hope you'll also think about building your own helpers within your applications, rather than duplicating common methods within each model.
As the Yii2 series progresses, I increasingly welcome feature and topic requests. You can post them in the comments below or email me at my Lookahead Consulting website.
If you'd like to know when the next Yii2 tutorial arrives, follow me @reifman on Twitter or check my instructor page. My instructor page will include all the articles from this series as soon as they are published.
To explore a more advanced Yii2 application now, check out our startup series and Meeting Planner. The application is now in alpha release, and you can schedule meetings with friends. You can also download the code; it's open source.
Comments