PHP Framework — Yii 2

Ashwin Vishwanath
9 min readJan 30, 2018

--

In this post, I am first going to introduce you to one of the most popular frameworks of PHP — Yii2, which is used in the development of Web Applications and ERP Applications. Secondly, I am going to discuss about an important extension of Yii known as Gii and how to generate CRUD in Yii using Gii.

Yii includes a handy tool Gii, that provides rapid prototyping by generating commonly used code snippets as well as complete CRUD controllers. Gii is a fast code generation tool, which I liked and will use in my upcoming projects. You will need a basic understanding of PHP in order to follow this tutorial.

Installing Yii will automatically install the Gii extension. So, to demonstrate Gii it is necessary that you know how to install Yii.

First, I will be discussing about Yii and then take you with a flow towards Gii. Secondly, i will be introducing you to few important code generators such as: “Model Generator” and “CRUD”, which i will be using in my upcoming projects.

Introduction to Yii

Yii is a high-performance, component-based PHP framework for fast programming of modern websites, is an acronym for “Yes It Is”!

Yii is a generic framework which can be used to encode all kinds of web applications that use PHP. As it follows a component-based architecture and sophisticated support for caching mechanisms, it is suitable for creating large applications like portals, forums, content management systems (CMS), commercial projects (e-stores), web services, ERP Applications and more.

Yii vs other PHP frameworks?

If you already familiar with another PHP framework, you can appreciate the following distinguished features:

  1. Like most of the other frameworks, Yii implements the MVC architecture (model-view-controller) and supports the organization of the code in line with this pattern.
  2. In Yii, code can be written in Y a simple approach. Yii does not try to divert the design pattern but follows the existing design patterns to keep the code simple.
  3. Yii provides tested and ready to use functionalities: query constructors and Active Record for relational databases and NoSql; support for RESTFull API; multi-stage caching support; and more.
  4. Yii is extremely expandable. You can customize or change almost any part of the core code. You can use the extension architecture to use or create easy-to-distribute extensions.
  5. High performance is the main key feature in Yii.

Requirements and Dependencies

  1. Yii 2.0 requires PHP 5.4.0 or newer version.
  2. More detailed requirements for specific functionalities can be checked by running the requirements tester requirements.php included in each Yii release.
  3. Using Yii requires basic knowledge of object-oriented programming in PHP (OOP). Yii 2, being a object-oriented framework uses the latest improvements in PHP such as namespaces.

Installing Yii

Before installing Yii make sure you have either WAMP/ XAMPP/ MAMP or LAMP servers installed based on the OS you use. Installing the server will install PHP, Apache and MySQL.

Yii can be installed in two ways

a) Using Composer

b) Manual Installation

Using Composer

Let me take you through the first method of installation via Composer

Steps to follow while installing Yii2 using Composer

  1. If you are a Linux or Mac OS X user, run the following commands in the command-line

curl -sS https://getcomposer.org/installer

php mv composer.phar /usr/local/bin/composer

If you are a Windows user, download the composer from the link — https://getcomposer.org/Composer-Setup.exe

During installation, provide path of php.exe file present in root folder of your server for command-line PHP.

2. After installing the composer in your command-line, access the root folder path and run the following command to update the composer to the latest version.

composer self-update

3. Install the Yii template.

To install the basic application template, run the command below:

php composer.phar create-project yiisoft/yii2-app-basic your-project-folder-name

To install the advanced application template, run the command below:

php composer.phar create-project yiisoft/yii2-app-advanced your-project-folder-name

This will successfully install Yii2 application in your root folder

Manual Installation

The second method of installation is Manual Installation

Steps to follow while installing Yii2 via Manual Installation

  1. Download the archive file that contains the Yii2 template

For basic template -https://github.com/yiisoft/yii2/releases/download/2.0.13/yii-basic-app-2.0.13.tgz

For advanced template -https://github.com/yiisoft/yii2/releases/download/2.0.13/yii-advanced-app-2.0.13.tgz

2. Next, unzip the archive file and add the unzipped Yii template to the root folder. Rename the template project folder.

3. Download the composer.phar from https://getcomposer.org/composer.phar

Add the downloaded file to the project folder.

4. Now open the command-line, access the project folder path and run the commands

composer update

php init

yii migrate

You can now access your installed Yii application from the URL

http://localhost/your-project-folder/web/index.php?r=site

This will navigate you to the screen as shown below

Yii successful installation

Successful installation of Yii also installs Gii.

The Gii tool

Gii provides a web-based interface for you to quickly generate the code you want. It also provides a command line interface for people who prefer to work with their console windows.

Installing and Configuring Gii

Gii is an official Yii extension. It will be automatically installed while installing Yii using composer or otherwise you can explicitly install it by running the command below

composer require “yiisoft/yii2-gii:*”

Also, you can add this line of code to the require section of your composer.json file:

“yiisoft/yii2-gii”: “*”

Then run the command composer update in your command line accessing the project folder path.

After the Gii extension has been installed, you should enable it by adding these lines to your application configuration file main.php. After enabling Gii, it is accessible from the URL

http://localhost/project-folder-name/web/index.php?r=gii

The above URL will navigate you to the screen as shown below

Gii includes different kinds of code generators that will handle the automatic code development also takes care of foreign key dependencies and connects the related models. The different code generators in Gii are as follows:

  1. Model Generator — Generates an ActiveRecord class for the specified database table. The database table is a populated on keyword suggestion and made easier to search a datatable.
  2. CRUD Generator — Generates a controller and corresponding views that implements CRUD (Create, Read, Update, Delete) operations for the specified data model. Also takes care of joins on table dependencies.
  3. Controller Generator — Generate a new controller, single or multiple controller actions and their corresponding views. Hence, implements the CRUD operations on these views.
  4. Form Generator — Generates a view file that displays a form based on a model class. Also, a controller action code is generated to be added in the corresponding controller, to support the view that is generated.
  5. Module Generator — Generates the pseudo code of a Yii module.
  6. Extension Generator — Generates the files of a Yii extension.

As Yii follows the MVC pattern, the framework contains the folders — models, controllers, views.

Model Generator

The Model Generator generates an ActiveRecord (Relational Database) class for the specified database table. The generated models are created in the models folder of the framework.

Click Start button under model generator to start creating Models.

Before that, create a table in your database. For example I am creating a Company table

CREATE TABLE IF NOT EXISTS `company` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`company_name` varchar(50) NOT NULL,
`company_address` varchar(100) NOT NULL,
`company_email` varchar(100) NOT NULL,
`created_on` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

Table Name

The name of the database table to which the new ActiveRecord class is associated with.

Type ‘company’ in the table name textbox

Model Class

The name of the ActiveRecord class to be generated.

The model class is auto-generated by Gii, which will start from capital letter.

Namespace

Namespace of the ActiveRecord class to be generated.

Namespace is generated. By default namespace is app\models

app can be replaced by either frontend or backend

Base Class

Base class of the new ActiveRecord class. By default the base class is yii\db\Activerecord

Database Connection ID

ID of the DB application component. By default the database connection object is db

Use Table Prefix

This indicates whether the table name of the generated ActiveRecord class should be added with a prefix with the DB connection.

For example, if the table name is tbl_employee, the ActiveRecord class will return the table name as {{%post}}

Generate relations

Generates relations based on foreign key constraints it detects in the database.

Generate Labels from DB Comments

Generates attribute labels by using the comments of the corresponding DB columns.

Enable I18N

Set this to true if you want to develop your application to translate into many languages.

Message Category

This category is used, if you enable I18N.

Code Template

Set of the templates should be used to generated the code.

Now Click “Preview” button, it will display the path of the code file that is generated. If you already created this Model and you want to overwrite it. Check the overwrite check box.

Then click “Generate” button to generate the files and your Model files is generated in @app\models\Model.

The demonstration can be seen in the screen shot below

Now ,I will show you how to generate CRUD once the Model is generated. Please note that, creating CRUD requires the creation of the associated model to begin with.

CRUD Generator

Creating web applications in PHP may lead in repetitive code. The Gii tool works for you like magic and creates the code needed to execute — Create,Read, Update, and Delete functions. In addition, it creates new Active Record Models, new Controllers, Forms, Modules, and extensions.

Now I will take you through procedure of making CRUD operations using Gii

Model Class

Add the model class of the data table you just created using Model Generator.

In my case, I have added frontend\models\Company. By default it is @app\models\Model. Do not forget to add namespace before the Model class.

Search Class

Here, add the same model class with the keyword “Search” appended at the end of the path. In my screen shot you can see frontend\models\CompanySearch.

This search model class contains the JOINS of the data table with the other tables in the database. This will allow the search of records based on the keywords you add in the tables of the index file.

Controller Class

Here the controller is created with the path along with the namespace. In the example I have added frontend\controllers\Company Controller. By default it is @app\controllers\CompanyController.

The keyword “Controller” is added at the end of the path.

View Path

The View path creates the CRUD views. By default Gii creates the below views to implement CRUD as shown below

_form.php — CREATE & UPDATE

_search.php — SEARCH

create.php — CREATE

update.php — UPDATE

view.php — READ

index.php — DATATABLE & DELETE

Now click on “Preview” to see the list of files to be created.

Now click on “Generate” to create views as shown below

Now the CRUD operation is successfully completed using Gii Tool. As simple as good, the CRUD operation is performed easily in very few simple steps.

The generated files are shown below. This will give you a rough idea of how the screen looks that is generated using crud

CREATE — VIEW — UPDATE — DELETE

http://localhost/project-folder-name/web/index.php?r=company/create
http://localhost/project-folder-name/web/index.php?r=company/view?id=1
http://localhost/project-folder-name/web/index.php?r=company/update?id=1
http://localhost/project-folder-name/web/index.php?r=company/delete?id=1
http://localhost/project-folder-name/web/index.php?r=company/index

In summary, Yii has many more options than most of the other frameworks of PHP to create robust web applications and ERP applications.The above mentioned are the code generators, which i would be using in my upcoming projects, but there are many more that one can utilize to create smarter and effecient applications.

--

--