Web Application Development with Yii 2 and PHP

4.7 (7 reviews total)
By Mark Safronov , Jeffrey Winesett
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Getting Started

About this book

Yii is a high performance PHP framework used for rapid web application development. It is well designed, well supported, easy to learn, and easy to maintain. This book embraces the learn-by-example methodology to show you the most important features of the Yii 2 framework. Throughout the course of this book, you will build a simple real-world application; each chapter will introduce you to a new functionality and show you how to tweak your application. Instead of trying to be an all-encompassing reference about the framework, this is a walkthrough of the really important pieces of information that you have to understand in detail.

You will learn how to use Yii's active record and CRUD scaffolding to manage the data in your database. Authentication, extensions, events and behaviors, and route management are just some of the many other features of Yii that you will learn from this book. By the end of this book, you will have a basic CRM application that is all set for service!

Publication date:
September 2014


Chapter 1. Getting Started

Let's see how we can set up a website with Yii 2 from scratch and with a minimum amount of effort. The goal is to learn about the installation procedure of the Yii application boilerplates offered by developers and the starting set of features provided in them.


A basic application

The most basic and straightforward way to get started with Yii 2 is to use the application boilerplate published by the Yii 2 team on their GitHub repository (https://github.com/yiisoft/yii2) and available through the Composer tool. In the prior versions of Yii, you had to manually download and extract the archive with the framework contents. While you can still do the same in Yii 2, this version is carefully crafted so that it's especially simple to install it using the Composer tool.

Installation of a basic application template

Find a suitable directory in your hard drive and fetch the Composer PHP archive (PHAR) into it in any way suitable for you, for example, using the following command:

$ curl -sS https://getcomposer.org/installer | php

Now run the following command to create a subdirectory called basic, and fill it with the basic application template:

$ php composer.phar create-project --prefer-dist --stability=dev \
yiisoft/yii2-app-basic basic


Please note that Yii 2 specifies several system-wide dependencies for itself. You probably will need to consult the composer.json file inside their GitHub repository to learn about them beforehand (https://github.com/yiisoft/yii2). But in any case, Composer will tell you what you need to install to make Yii 2 workable. Yii 2 gets new updates quite often and its requirements are a moving target.

It's a line split into two lines for readability, with a slash denoting the overflow of the command line to the next line of text. Shell interpreters on Unix-like systems should understand this convention, so you can probably just copy and paste the code verbatim and it'll be executed correctly. You better check the documentation of Composer for the meaning of the beginning of the preceding command, but the part relevant to us is yiisoft/yii2-app-basic basic, which means "copy contents of the repo published at https://github.com/yiisoft/yii2-app-basic to our local folder named basic." The command will install the project skeleton in the form of a set of predefined folders, and among them the vendor subdirectory, which contains quite a lot of other Composer packages. Inside the basic folder will be your application root.

After Composer finishes installing the required packages, you can just issue the following command:

$ php -S localhost:8000 –t basic/web

Here, 8000 is the port number, which you can change to anything you want. This will launch the web server built into PHP.


This is not the preferred setup for PHP-based web applications, of course. The built-in web server was used only as a "smoke test" to verify that everything in general works. It is suitable only for local development without a heavy load. The next chapter will deal with the real-world deployment of a Yii-based web application.

Point your web browser at the http://localhost:8000/ URL. You should see the welcome page for the Yii 2 application, which means that you're done setting things up.

Specifics of the basic application template

You can get a comprehensive overview of the various folders inside the basic template by reading the README file provided with the template (https://github.com/yiisoft/yii2/blob/master/apps/basic/README.md), or by reading the global Yii 2 documentation page describing basic applications (http://www.yiiframework.com/doc-2.0/guide-start-installation.html).

The most important thing you should understand is that the publicly available web root directory is just one folder in the overall code base. It's the web directory for our basic application. Every other folder is outside the web root directory, that is, out of reach for the web server.

As you have already seen in the installation description, given that you have PHP and, optionally, curl, this code base is ready to use right from the start; no specific environment is needed to be set up. All the dependencies are managed through the Composer tool.

A three-tier automatic testing harness is already set up in the basic template. It contains acceptance, functional, and unit tests covering most of the functionalities. The tests already included in the template are useful as examples that show how to utilize the testing framework used, which is Codeception (http://codeception.com/).

The template can be really useful to you if all you need is something like a news feed feature or a web tool spanning a couple of pages. However, the absence of separation by subsystems, such as the administrative backend and public frontend, will start to hinder you on a larger web application; probably, an application with more than just 10 unique routes.

Note that by reading the project dependencies in the composer.json file, Yii 2 has several important parts separated out as pluggable packages, and they are already included in your code base by Composer. These packages are listed as follows:

  • Gii, the code generator, which we will discuss in detail in Chapter 3, Automatically Generating the CRUD Code

  • The debug console that is already enabled on the basic application template

  • A wrapper around the Codeception testing framework

  • A wrapper around the SwiftMailer library (http://swiftmailer.org/), which can be found at https://github.com/yiisoft/yii2-swiftmailer

  • The Twitter Bootstrap UI library packaged as a Yii 2 asset bundle (it's practically ubiquitous nowadays, but here's the link anyway: http://getbootstrap.com/)

The first three are set up so that you get them only when you are developing the application, since they are useless and even harmful in the production environment. Most probably, you'll need all of these on any serious project though.


A short overview of the basic application installation:

$ curl -sS https://getcomposer.org/installer | php
$ php composer.phar create-project --prefer-dist \--stability=dev yiisoft/yii2-app-basic basic
$ php -S localhost:8000 -t basic/web

An advanced application

Apart from the basic application template, Yii 2 has an advanced application template. It's geared more towards medium-sized applications (such as applications that are really useful to businesses), and its main feature is two separate web interfaces: one dedicated to content management and the other to presenting this content to visitors. So, you get an almost complete CMS skeleton with this template.

Installation of an advanced application template

The first steps are the same as for a basic template. You need to fetch the Composer executable and set up a new project using it:

$ curl -sS https://getcomposer.org/installer | php
$ php composer.phar create-project --prefer-dist --stability=dev \
yiisoft/yii2-app-advanced advanced

You can see that the difference is just that instead of the word "basic", we use the word "advanced".

Now, let's make further changes. First, go to the newly created directory named advanced. After this, you need to generate the required local configuration by running the following command:

$ ./init

Yes, it's just the init script from the root of the code base. It'll ask you whether you want a development mode or a production mode and create all the necessary auxiliary configuration snippets and entry scripts. To be precise, it just copies the contents of the dev or prod folders from the environments subdirectory depending on whether you selected the development environment or the production one. Just open the environments subdirectory and you'll understand how it works.

Next, you need to create the database to be used by this application. By default, for configuration of a development environment, you have to set up a MySQL database named yii2advanced accessible from the localhost at the default MySQL port for user root without any password. You can see the details in the common/config/main-local.php file.

Given that you have the database set up, you need to run migrations. We'll talk about migration scripts in the next chapter (and we will even write several scripts ourselves), but if the very concept of database migrations is foreign to you, you can read about it in the official documentation at the Yii 2 website (at the time of writing this, there is no official documentation, but the framework has the docs included in the GitHub repository at https://github.com/yiisoft/yii2/blob/master/docs/guide/db-migrations.md).

Just run the following command anyway:

$ ./yii migrate

It'll present you with a list of exactly one migration and ask you for confirmation before doing its job.

Now, you are ready. Make both the sides of the application accessible for you by executing the following commands:

$ php -S localhost:8080 -t frontend/web
$ php -S localhost:8081 -t backend/web

As with the basic application template, we are using the built-in PHP web server just because it's a lot simpler to be demonstrated in the book than explain how to set up Apache or some other web server to serve from these folders.

Now you'll have the backend side of the application intended to be used by content managers and the frontend side of the application intended to be the website your visitors will see. Also, note that you have a completely controllable console runner launched by the yii script you used when doing migrations.

Advanced application has exactly the same frontend as basic application. Here is how its backend looks like:

The advanced template backend is locked down initially. After logging in, you get the same page as the one from the basic template or the advanced template frontend, but with only the login feature in the menu.

Specifics of the advanced application template

The most important thing about the advanced application template is that it is three basic application templates wired together as one:

  • Inside the frontend folder is the application structure for the public-facing side of your website. Real functionalities and the content of your website or web application is expected to be placed here.

  • The folder named backend is for your CMS, protected from unauthorized access. You are expected to place all of your admin-accessible CRUD here.

  • The console folder is mainly for your custom console commands, in hope you'll have any, and a lot more likely, for your migration scripts.

  • The common folder contains code that will be used by all the entry points, since it's a single application after all.

Of course, nobody forces you to use the frontend and backend sides as described. You just have two web frontends sharing the same code base, so you are free to use them as you wish. However, the UI already prepared for the advanced template that has a password-protected backend right from the start.

You should know about the login feature for the freshly installed advanced application template. Initially, it had no users defined, and you had to create one by utilizing the signup feature at the frontend. After that, you'll be able to login to both backend and frontend using the created credentials. The frontend is identical to the basic application, and the backend is stripped of everything except the login feature and front page, so everything is up to you.


A short overview of the installation of the advanced application:

$ curl -sS https://getcomposer.org/installer | php
$ php composer.phar create-project --prefer-dist \
--stability=dev yiisoft/yii2-app-advanced advanced
$ cd advanced
$ ./init
$ mysql -u root -e 'create database yii2advanced'
$./yii migrate
$ php -S localhost:8080 -t frontend/web
$ php -S localhost:8081 -t backend/web


Yii 2 allows you to configure almost all paths used by the framework, and hence you can create any directory tree you wish. By utilizing the PHP 5.3 namespaces wisely, you can even have a physical structure of your project different from the logical one, that is, your files will lie in folders differently from how your classes are structured by namespaces. This will surely be quite tedious to do though.

In the next chapter, we'll look at how we can utilize Yii in a (albeit small) real-world project, built completely from scratch, and without using the templates we saw in this chapter.

About the Authors

  • Mark Safronov

    Mark Safronov is a professional web application developer from the Russian Federation, with experience and interest in a wide range of programming languages and technologies. He has built and participated in building different types of web applications, from pure computational ones to full-blown e-commerce sites. He is also a proponent of following the current best practices of test-first development and clean and maintainable code.

    He is currently employed at Clevertech and is working on Yii-based PHP web applications. He was also a maintainer of the popular YiiBooster open source extension for some time.

    Back in 2008, he translated the book Visual Prolog 7.1 for Tyros, Eduardo Costa, in Russian with a totally new color layout. In 2013, along with Jacob Mumm, he co-authored the book Instant Yii Application Development Starter, Packt Publishing.

    Browse publications by this author
  • Jeffrey Winesett

    Jeffrey Winesett is a partner at SeeSaw Labs in Austin, Texas, and has over 10 years of experience building large-scale, web-based applications. He is a strong proponent of using open source development frameworks when developing applications, and a champion of the Yii framework in particular since its initial alpha release. He frequently presents on, writes about, and develops with Yii as often as possible.

    Browse publications by this author

Latest Reviews

(7 reviews total)
Guter Preis, schnelle Lieferung, dazu noch ein nicht DRM-verseuchtes PDF des Buchs dazu (gedruckte Fachbücher lassen sich nur schwer mit STRG+F durchsuchen..) -> ich bin sehr zufrieden.
The book gets you started fast and you wonder why you tried out node.js earlier in the first place.
I liked the clear structure of the book, the clean and thorough methodology, and the author's approach to software development (Building the domain model, Setting up the testing harness, Setting up the deployment pipeline, The Red-Green-Refactor development cycle, Deployment and manual tests).
Web Application Development with Yii 2 and PHP
Unlock this book and the full library for FREE
Start free trial