Wednesday, March 22, 2017

Yii - Overview

The Yii[ji:] framework is an open-source PHP framework for rapidly-developing, modern Web applications. It is built around the Model-View-Controller composite pattern.
Yii provides secure and professional features to create robust projects rapidly. The Yii framework has a component-based architecture and a full solid caching support.

Yii - Installation

The most straightforward way to get started with Yii2 is to use the basic application template provided by the Yii2 team. This template is also available through the Composer tool.
Step 1 − Find a suitable directory in your hard drive and download the Composer PHAR (PHP archive) via the following command.

Yii - Create Page

Now we are going to create a “Hello world” page in your application. To create a page, we must create an action and a view.
Actions are declared in controllers. The end user will receive the execution result of an action.
Step 1 − Declare the speak action in the existing SiteController, which is defined in the class file controllers/SiteController.php.

Yii - Application Structure

There is only one folder in the overall code base that is publicly available for the web server. It is the web directory. Other folders outside the web root directory are out of reach for the web server.
Note − All project dependencies are located in the composer.json file. Yii2 has a few important packages that are already included in your project by Composer. These packages are the following −

Yii - Entry Scripts

Entry scripts are responsible for starting a request handling cycle. They are just PHP scripts accessible by users.
The following illustration shows the structure of an application −

Yii - Controllers

Controllers are responsible for processing requests and generating responses. After user's request, the controller will analyze request data, pass them to model, then insert the model result into a view, and generate a response.

Yii - Using Controllers

Controllers in web applications should extend from yii\web\Controller or its child classes. In console applications, they should extend from yii\console\Controller or its child classes.
Let us create an example controller in the controllers folder.

Yii - Using Actions

To create an action in a controller class, you should define a public method whose name starts with the word action. The return data of an action represents the response to be sent to the end user.
Step 1 − Let us define the hello-world action in our ExampleController.
<?php 

Yii - Models

Models are objects representing business logic and rules. To create a model, you should extend the yii\base\Model class or its subclasses.

Attributes

Attributes represent the business data. They can be accessed like array elements or object properties. Each attribute is a publicly accessible property of a model. To specify what attributes a model possesses, you should override the yii\base\Model::attributes() method.
Let us have a look at the ContactForm model of the basic application template.

Yii - Widgets

A widget is a reusable client-side code, which contains HTML, CSS, and JS. This code includes minimal logic and is wrapped in a yii\base\Widget object. We can easily insert and apply this object in any view.
Step 1 − To see widgets in action, create an actionTestWidget function in the SiteController with the following code.

Yii - Modules

A module is an entity that has its own models, views, controllers, and possibly other modules. It is practically an application inside the application.
Step 1 − Create a folder called modules inside your project root. Inside the modules folder, create a folder named hello. This will be the basic folder for our Hello module.
Step 2 − Inside the hello folder, create a file Hello.php with the following code.

Yii - Views

Views are responsible for presenting the data to end users. In web applications, Views are just PHP script files containing HTML and PHP code.

Creating Views

Step 1 − Let us have a look at the ‘About’ view of the basic application template.
<?php
   /* @var $this yii\web\View */
   use yii\helpers\Html;
   $this->title = 'About';

Yii - Layouts

Layouts represent the common parts of multiple views i.e. for example, page header and footer. By default, layouts should be stored in the views/layouts folder.
Let us have a look at the main layout of the basic application template −

Yii - Assets

An asset is a file (css, js, video, audio or image, etc.) that may be referenced in a web page. Yii manages assets in asset bundles. The purpose of an asset bundle is to have a group of related JS or CSS files in the code base and to be able to register them within a single PHP call. Asset bundles can also depend on other asset bundles.

Yii - Asset Conversion

Instead of writing CSS or JS code, developers often use extended syntax, like LESS, SCSS, Stylus for CSS and TypeScript, CoffeeScript for JS. Then they use special tools to convert these files into real CSS and JS.

Yii - Extensions

Extensions are packages specifically designed to be used in Yii applications. You can share your own code as an extension or use third-party extensions to add features to your application.

Using Extensions

Most extensions are distributed as Composer packages. Composer installs packages from Packagist – the repository for Composer packages.
To install a third-party extension, you should −

Yii - Creating Extensions

Let us create a simple extension displaying a standard “Hello world” message. This extension will be distributed via the Packagist repository.
Step 1 − Create a folder called hello-world in your hard drive but not inside the Yii basic application template). Inside the hello-world directory, create a file named composer.json with the following code.

Yii - HTTP Requests

Requests are represented by the yii\web\Request object, which provides information about HTTP headers, request parameters, cookies, and so forth.
The methods get() and post() return request parameters of the request component.
Example

Yii - Responses

When a web application handles a request, it generates a response object, which contains HTTP headers, body, and HTTP status code. In most cases, you will use the response application component. By default, it is an instance of yii\web\Response.

Yii - URL Formats

When a Yii application processes a requested URL, first, it parses the URL into a route. Then, to handle the request, this route is used to instantiate the corresponding controller action. This process is called routing. The reverse process is called URL creation. The urlManager application component is responsible for routing and URL creation. It provides two methods −

Yii - URL Routing

To change the default route of the application, you should configure the defaultRoute property.
Step 1 − Modify the config/web.php file in the following way.
<?php
   $params = require(__DIR__ . '/params.php');
   $config = [
      'id' => 'basic',

Yii - Rules of URL

A URL rule is an instance if yii\web\UrlRule. The urlManager components uses the URL rules declared in its rules property when the pretty URL format is enabled.
To parse a request, the URL manager obtains the rules in the order they are declared and looks for the first rule.

Yii - HTML Forms

When a form is based upon a model, the common way of creating this form in Yii is via the yii\widgets\ActiveForm class. In most cases, a form has a corresponding model which is used for data validation. If the model represents data from a database, then the model should be derived from the ActiveRecord class. If the model captures arbitrary input, it should be derived from the yii\base\Model class.

Yii - Validation

You should never trust the data received from users. To validate a model with user inputs, you should call yii\base\Model::validate() method. It returns a Boolean value if the validation succeeds. If there are errors, you may get them from the yii\base\Model::$errors property.

Yii - Ad Hoc Validation

Sometimes you need to validate values that are not bound to any model. You can use the yii\base\DynamicModel class, which supports defining both attributes and rules on the fly.
Step 1 − Add the actionAdHocValidation method to the SiteController.

Yii - AJAX Validation

The username validation should only be done on the server side because only the server has the needed information. In this case, you can use AJAX-based validation.
Step 1 − To enable the AJAX validation, modify the registration view this way.
<?php
   use yii\bootstrap\ActiveForm;
   use yii\bootstrap\Html;
?>

Yii - Sessions

Sessions make data accessible across various pages. A session creates a file on the server in a temporary directory where all session variables are stored. This data is available to all the pages of your web site during the visit of that particular user.
When a session starts, the following happens −

Yii - Using Flash Data

Yii provides a concept of flash data. Flash data is a session data which −
  • Is set in one request.
  • Will only be available on the next request.
  • Will be automatically deleted afterwards.

Yii - Cookies

Cookies are plain text files stored on the client side. You can use them for tracking purpose.
There are three steps to identify a returning user −
  • Server sends a set of cookies to the client (browser). For example, id or token.
  • Browser stores it.
  • Next time a browser sends a request to the web server, it also sends those cookies, so that the server can use that information to identify the user.

Yii - Using Cookies

Cookies allow data to be persisted across requests. In PHP, you may access them through the $_COOKIE variable. Yii represents cookie as an object of the yii\web\Cookie class. In this chapter, we describe several methods for reading cookies.

Yii - Files Upload

You can easily implement a file uploading function with the help of yii\web\UploadedFile, models and yii\widgets\ActiveForm.
Create a directory ‘uploads’ in the root folder. This directory will hold all of the uploaded images. To upload a single file, you need to create a model and an attribute of the model for uploaded file instance. You should also validate the file upload.

Yii - Formatting

To display data in a readable format, you can use the formatter application component.
Step1 − Add the actionFormatter method to the SiteController.
public function actionFormatter(){
   return $this->render('formatter');

Yii - Pagination

When you have too much data to display on a single page, you should display it on multiple pages. This is also known as pagination.
To show pagination in action, we need data.

Yii - Sorting

When displaying lots of data, we often need to sort the data. Yii uses an yii\data\Sort object to represent a sorting schema.
To show sorting in action, we need data.

Yii - Properties

Class member variables in PHP are also called properties. They represent the state of class instance. Yii introduces a class called yii\base\Object. It supports defining properties via getter or setter class methods.
A getter method starts with the word get. A setter method starts with set. You can use properties defined by getters and setters like class member variables.

Yii - Data Providers

Yii provides a set of data provider classes that encapsulate pagination and sorting. A data provider implements yii\data\DataProviderInterface. It supports retrieving sorted and paginated data. Data providers usually work with data widgets.
Yii includes −

Yii - Data Widgets

Yii provides a set of widgets for displaying data. You can use the DetailView widget to display a single record. The ListView widget, as well as Grid View, can be used to display a table of records with features like filtering, sorting, and pagination.

Yii - ListView Widget

The ListView widget uses a data provider to display data. Each model is rendered using the specified view file.
Step 1 − Modify the actionDataWidget() method this way.
public function actionDataWidget() {
   $dataProvider = new ActiveDataProvider([
      'query' => MyUser::find(),
      'pagination' => [
         'pageSize' => 20,

Yii - GridView Widget

The GridView widget takes data from a data provider and presents data in the form of a table. Each row of the table represents a single data item, and a column represents an attribute of the item.
Step 1 − Modify the datawidget view this way.
<?php
   use yii\grid\GridView;
   echo GridView::widget([
      'dataProvider' => $dataProvider,

Yii - Events

You can use events to inject custom code at certain execution points. You can attach custom code to an event, and when the event is triggered, the code gets executed. For example, a logger object may trigger a userRegistered event when a new user registers on your web site. If a class needs to trigger events, you should extend it from the yii\base\Component class.
An event handler is a PHP callback. You can use the following callbacks −

Yii - Creating Event

In this chapter we will see to create an event in Yii. To show events in action, we need data.

Preparing the DB

Step 1 − Create a new database. Database can be prepared in the following two ways.
  • In the terminal run mysql -u root –p
  • Create a new database via CREATE DATABASE helloworld CHARACTER SET utf8 COLLATE utf8_general_ci;

Yii - Behaviors

Behaviors are instances of the yii\base\Behavior class. A behavior injects its methods and properties to the component it is attached to. Behaviors can also respond to the events triggered by the component.
Step 1 − To define a behavior, extend the yii\base\Behavior class.

Yii - Creating a Behavior

Assume we want to create a behavior that will uppercase the “name” property of the component the behavior is attached to.
Step 1 − Inside the components folder, create a file called UppercaseBehavior.php with the following code.
<?php

Yii - Configurations

Configurations are used to create new objects or initializing the existing ones. Configurations usually include a class name and a list of initial values. They may also include a list of event handlers and behaviors.
The following is an example of the database configuration −
<?php

Yii - Dependency Injection

A DI(dependency injection) container is an object that knows how to instantiate and configure objects. Yii provides the DI container via the yii\di\Container class.
It supports the following kinds of DI −
  • Setter and property injection
  • PHP callable injection
  • Constructor injection
  • Controller action injection

Yii - Database Access

Yii DAO (Database Access Object) provides an API for accessing databases. It also serves as the foundation for other database access methods: active record and query builder.
Yii DAO supports the following databases −

Yii - Data Access Objects

To execute an SQL query, you should follow these steps −
  • Create an yii\db\Command with an SQL query.
  • Bind parameters (not required)
  • Execute the command.

Yii - Query Builder

Query builder allows you to create SQL queries in a programmatic way. Query builder helps you write more readable SQL-related code.
To use query builder, you should follow these steps −
  • Build an yii\db\Query object.
  • Execute a query method.

Yii - Active Record

Active Record provides an object-oriented API for accessing data. An Active Record class is associated with a database table.
Yii provides the Active Record support for the following relational databases −

Yii - Database Migration

During the developing of a database-driven application, the database structure evolves with the source code. Yii provides the database migration feature that allows you to keep track of database changes.
Yii provides the following migration command line tools −

Yii - Theming

Theming helps you replace a set of views with another one without the need of modifying original view files. You should set the theme property of the view application component to use theming.
You should also define the following properties −

Yii - RESTful APIs

Yii provides the following useful features for implementing RESTful APIs −
  • Quick prototyping
  • Customizable object serialization
  • Response format (supporting JSON and XML by default)
  • Formatting of collection data and validation errors
  • Efficient routing

Yii - RESTful APIs in Action

The controller class extends from the yii\rest\ActiveController class, which implements common RESTful actions. We specify the $modelClass property so that the controller knows which model to use for manipulating data.
Step 1 − Create a file called UserController.php inside the controllers folder.
<?php

Yii - Fields

By overriding fields() and extraFields() methods, you can define what data can be put into a response. The difference between these two methods is that the former defines the default set of fields, which should be included in the response while the latter defines additional fields, which may be included in the response if an end user requests for them via the expand query parameter.

Yii - Testing

When we write a PHP class, we debug it step by step or use die or echo statements to verify how it works. If we develop a web application, we are entering test data in forms to ensure the page works as we expected. This test process can be automated.
Automatic test approach makes sense for long term projects, which are −

Yii - Caching

Caching is an effective way to improve the performance of your application. Caching mechanisms store static data in cache and get it from cache when requested. On the server side, you may use cache to store basic data, such as a list of most recent news. You can also store page fragments or whole web pages. On the client side, you can use HTTP caching to keep most recently visited pages in the browser cache.

Yii - Fragment Caching

Fragment caching provides caching of a fragment of a web page.
Step 1 − Add a new function called actionFragmentCaching() to the SiteController.
public function actionFragmentCaching() {
   $user = new MyUser();
   $user->name = "cached user name";

Yii - Aliases

Aliases help you not to hard-code absolute paths or URLs in your project. An alias starts with the @ character.
To define an alias you should call the Yii::setAlias() method −
// an alias of a file path
Yii::setAlias('@alias', '/path/to/alias');
// an alias of a URL

Yii - Logging

Yii provides a highly customizable and extensible framework. With the help of this framework, you can easily log various types of messages.
To log a message, you should call one of the following methods −
  • Yii::error() − Records a fatal error message.
  • Yii::warning() − Records a warning message.
  • Yii::info() − Records a message with some useful information.
  • Yii::trace() − Records a message to trace how a piece of code runs.

Yii - Error Handling

Yii includes a built-in error handler. The Yii error handler does the following −
  • Converts all non-fatal PHP errors into catchable exceptions.
  • Displays all errors and exceptions with a detailed call stack.
  • Supports different error formats.
  • Supports using a controller action to display errors.

Yii - Authentication

The process of verifying the identity of a user is called authentication. It usually uses a username and a password to judge whether the user is one who he claims as.
To use the Yii authentication framework, you need to −

Yii - Authorization

The process of verifying that a user has enough permission to do something is called authorization. Yii provides an ACF (Access Control Filter), an authorization method implemented as yii\filters\AccessControl. Modify the behaviors() function of the SiteController −

Yii - Localization

I18N (Internationalization) is the process of designing an application that can be adapted to various languages. Yii offers a full spectrum of I18N features.
Locale is a set of parameters that specify a user's language and country. For example, the en-US stands for the English locale and the United States.

Yii - Gii

Gii is the extension, that provides a web-based code generator for generating models, forms, modules, CRUD, and so forth.
By default, the following generators are available −
  • Model Generator − Generates an ActiveRecord class for the specified database table.
  • CRUD Generator − Generates a controller and views that implement CRUD (Create, Read, Update, Delete) operations for the specified model.

Gii - Creating a Model

To create a Model in Gii −
<?php
   namespace app\models;
   use app\components\UppercaseBehavior;
   use Yii;
   /**

Gii - Generating Controller

Let us see how to generate a Controller.
Step 1 − To generate a controller with several actions, open the controller generator interface fill in the form.

Gii - Generating Module

Let us see how to generate a Module.
Step 1 − To generate a module, open the module generation interface and fill in the form.

Yii - Quick Guide

Yii - Overview

The Yii[ji:] framework is an open-source PHP framework for rapidly-developing, modern Web applications. It is built around the Model-View-Controller composite pattern.
Yii provides secure and professional features to create robust projects rapidly.

Yii - Useful Resources

The following resources contain additional information on Yii. Please use them to get more in-depth knowledge on this.

Useful Links on Yii

Discuss Yii

The Yii[ji:] framework is an open-source PHP framework for rapidly-developing, modern Web applications. It is built around the Model-View-Controller composite pattern. Yii provides secure and professional features to create robust projects rapidly.