Web Application Development with Yii and PHP

4 (1 reviews total)
By Jeffrey Winesett
  • 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. Meet Yii

About this book

This book is a step by step tutorial in developing a real-world application using the incremental and iterative approach to software development. You learn about agile software development by leaning on the agile nature of the Yii application development framework. You touch on each aspect of the software development lifecycle by building a project task management application from concept through production deployment.

After a brief, general introduction to the Yii framework and outlining the software development approach taken throughout the book, the chapters break down in the same way as software development iterations do in real-world projects. After the 1st iteration, you will have a working and tested application with a valid, tested connection to a database.

In the 2nd and 3rd iterations, we flesh out our main database entities and domain object model and become familiar with Yii's object-relational-mapping (ORM) layer, Active Record. We also learn how to lean on Yii's auto-generation tools to automatically build our create/read/update/delete (CRUD) functionality against our newly created model. These iterations also focus on how Yii's form validation and submission model works. By the end of the third iteration you will have a working application that allows you to mange projects and issues (tasks) within those projects.

The 4th and 5th iterations are dedicated to user management. We learn about the built-in authentication model within Yii to assist in application login and logout functionality. We then dive into the authorization model, first taking advantage of a Yii's simple access control model, then implementing the more sophisticated role-based access control (RBAC) framework that Yii provides.

By the end of the 5th iteration, all of the basics of a task management application are in place. The next several iterations are focused on the nice-to-haves. We add user comment functionality, introducing a reusable content portlet architecture approach in the process. We add in an RSS Web feed and demonstrate how easy it is to integrate other third-party tools within a Yii application. We take advantage of Yii's theming structure to help streamline and design the application, and then introduce Yii's internationalization (I18N) features so the application can be adapted to various languages and regions without engineering changes.

Finally, we turn our focus to production deployment. We introduce ways to optimize performance and security to prepare the application for a real-world production environment.

Publication date:
November 2012


Chapter 1. Meet Yii

Web development frameworks help jump-start your application by immediately delivering the core foundation and plumbing needed to quickly turn your ideas scribbled on the whiteboard into functional, production-ready code. With all of the common features expected from web applications today, and available framework options that meet these expectations, there is little reason to code your next web application from scratch. A modern, flexible, and extensible framework is almost as essential a tool to today's web developer as the programming language itself. And when the two are particularly complementary, the results are an extremely powerful toolkit—Java and Spring, Ruby and Rails, C# and .NET, and PHP and Yii.

Yii is the brainchild of founder Qiang Xue, who started the development of this open source framework on January 1, 2008. Qiang had previously developed and maintained the PRADO framework for many years prior to starting this. The years of experience and user feedback cultivated from the PRADO project solidified the need for a much easier, more extensible, and more efficient PHP5-based framework, to meet the ever-growing needs of application developers. The initial alpha version of Yii was officially released to meet these needs in October of 2008. Its extremely impressive performance metrics when compared to other PHP-based frameworks immediately drew very positive attention. On December 3, 2008, Yii 1.0 was officially released, and as of Oct 1, 2012, the latest production-ready version is up to 1.1.12. It has a growing development team and continues to gain in popularity among PHP developers everyday.

The name Yii is an acronym for Yes, it is, and is pronounced as Yee or (ji:). Yii is a high-performance, component-based, web application framework written in PHP5. The name is also representative of the adjectives most used to describe it, such as easy, efficient, and extensible. Let's take a quick look at each of these characteristics of Yii, turn by turn.



To run a Yii version 1.x-powered web application, all you need are the core framework files and a web server supporting PHP 5.1.0 or higher. To develop with Yii, you only need to know PHP and object-oriented programming. You are not required to learn any new configuration or templating language. Building a Yii application mainly involves writing and maintaining your own custom PHP classes, some of which will extend from the core, Yii framework component classes.

Yii incorporates many of the great ideas and work from other well-known web programming frameworks and applications. So if you are coming to Yii from using other web development frameworks, it is likely that you will find it familiar and easy to navigate.

Yii also embraces a convention over configuration philosophy, which contributes to its ease of use. This means that Yii has sensible defaults for almost all the aspects that are used for configuring your application. Following the prescribed conventions, you can write less code and spend less time developing your application. However, Yii does not force your hand. It allows you to customize all of its defaults and makes it easy to override all of these conventions. We will be covering some of these defaults and conventions later in this chapter and throughout the book.



Yii is a high-performance, component-based framework that can be used for developing web applications on any scale. It encourages maximum code reuse in web programming and can significantly accelerate the development process. As mentioned previously, if you stick with Yii's built-in conventions, you can get your application up and running with little or no manual configuration.

Yii is also designed to help you with DRY development. DRY stands for Don't Repeat Yourself , a key concept of agile application development. All Yii applications are built using the Model-View-Controller (MVC) architecture. Yii enforces this development pattern by providing a place to keep each piece of your MVC code. This minimizes duplication and helps promote code reuse and ease of maintainability. The less code you need to write, the less time it takes to get your application to market. The easier it is to maintain your application, the longer it will stay on the market.

Of course, the framework is not just efficient to use, it is remarkably fast and performance optimized. Yii has been developed with performance optimization in mind from the very beginning, and the result is one of the most efficient PHP frameworks around. So any additional overhead that Yii adds to applications written on top of it is extremely negligible.



Yii has been carefully designed to allow nearly every piece of its code to be extended and customized to meet any project requirement. In fact, it is difficult not to take advantage of Yii's ease of extensibility, since a primary activity when developing a Yii application is extending the core framework classes. And if you want to turn your extended code into useful tools for other developers, Yii provides easy-to-follow steps and guidelines to help you create such third-party extensions. This allows you to contribute to Yii's ever-growing list of features and actively participate in extending Yii itself.

Remarkably, this ease-of-use, superior performance, and depth of extensibility does not come at the cost of sacrificing its features. Yii is packed with features to help you meet those high demands placed on today's web applications. AJAX-enabled widgets, RESTful and SOAP Web services integration, enforcement of an MVC architecture, DAO and relational ActiveRecord database layer, sophisticated caching, hierarchical role-based access control, theming, internationalization (I18N), and localization (L10N) are just the tip of the Yii iceberg. As of version 1.1, the core framework is now packaged with an official extension library called Zii. These extensions are developed and maintained by the core framework team members, and continue to extend Yii's core feature set. And with a deep community of users who are also contributing by writing Yii extensions, the overall feature set available to a Yii-powered application is growing daily. A list of available, user-contributed extensions on the Yii framework website can be found at http://www.yiiframework.com/extensions. There is also an unofficial extension repository of great extensions that can be found at http://yiiext.github.com/, which really demonstrates the strength of the community and the extensibility of this framework.


MVC architecture

As mentioned earlier, Yii is an MVC framework and provides an explicit directory structure for each piece of model, view, and controller code. Before we get started with building our first Yii application, we need to define a few key terms and look at how Yii implements and enforces this MVC architecture.


Typically in an MVC architecture, the model is responsible for maintaining the state, and should encapsulate the business rules that apply to the data that defines this state. A model in Yii is any instance of the framework class CModel or its child class. A model class is typically comprised of data attributes that can have separate labels (something user friendly for the purpose of display), and can be validated against a set of rules defined in the model. The data that makes up the attributes in the model class could come from a row of a database table or from the fields in a user input form.

Yii implements two kinds of models, namely the form model (a CFormModel class) and active record (a CActiveRecord class). They both extend from the same base class CModel. The class CFormModel represents a data model that collects HTML form inputs. It encapsulates all the logic for form field validation, and any other business logic that may need to be applied to the form field data. It can then store this data in memory or, with the help of an active record model, store data in a database.

Active Record (AR) is a design pattern used to abstract database access in an object-oriented fashion. Each AR object in Yii is an instance of CActiveRecord or its child class, which wraps a single row in a database table or view, that encapsulates all the logic and details around database access, and houses much of the business logic that is required to be applied to that data. The data field values for each column in the table row are represented as properties of the active record object. Active Record is described in more detail a little later.


Typically the view is responsible for rendering the user interface, often based on the data in the model. A view in Yii is a PHP script that contains user interface-related elements, often built using HTML, but can also contain PHP statements. Usually, any PHP statements within the view are very simple, conditional or looping statements, or refer to other Yii UI-related elements such as HTML helper class methods or prebuilt widgets. More sophisticated logic should be separated from the view and placed appropriately in either the model, if dealing directly with the data, or the controller, for more general business logic.


The controller is our main director of a routed request, and is responsible for taking user input, interacting with the model, and instructing the view to update and display appropriately. A controller in Yii is an instance of CController or a child class thereof. When a controller runs, it performs the requested action, which then interacts with the necessary models, and renders an appropriate view. An action, in its simplest form, is a controller class method whose name starts with the word action.


Stitching these together: Yii request routing

In MVC implementations, a web request typically has the following life cycle:

  • The browser sends a request to the server hosting the MVC application

  • A controller action is invoked to handle the request

  • The controller interacts with the model

  • The controller invokes the view

  • The view renders the data (often as HTML) and returns it to the browser for display

Yii's MVC implementation is no exception. In a Yii application, incoming requests from the browser are first received by a router. The router analyzes the request to decide where in the application it should be sent for further processing. In most cases, the router identifies a specific action method within a controller class to which the request is passed. This action method will look at the incoming request data, possibly interact with the model, and perform other needed business logic. Eventually, this action method will prepare the response data and send it to the view. The view will then format this data to conform to the desired layout and design, and return it for the browser to display.

Blog posting example

To help all of this make more sense, let's look at a fictitious example. Let's pretend that we have used Yii to build ourselves a new blog site http://yourblog.com. This site is like most typical blog sites out there. The home page displays a list of recently posted blog posts. The names of each of these blog postings are hyperlinks that take the user to the page that displays the full article. The following diagram illustrates how Yii handles an incoming request sent from clicking on one of these hypothetical blog post links:

The figure traces the request that is made from a user clicking on the link:http://yourblog.com/post/show/id/99

First the request is sent to the router. The router parses the request, to decide where to send it. The structure of the URL is key to the decision that the router will make. By default, Yii recognizes URLs with the following format:


The r querystring variable refers to the route that is analyzed by the Yii router. It will parse this route to determine the appropriate controller and action method, to further handle the request. Now you may have immediately noticed that our example URL above does not follow this default format. It is a very simple matter of configuring the application to recognize the URLs in the following format:


We will continue to use this simplified format for the purposes of this example. The ControllerID name in the URL refers to the name of the controller. By default this is the first part of the controller class name, up to the word Controller. So for example, if your controller class name is TestController, the ControllerID name would be test. ActionID similarly refers to the name of the action that is defined by the controller. If the action is a simple method defined within the controller, this will be whatever follows the word action in the method name. For example, if your action method is named actionCreate(), the ActionID name is create.


If the ActionID is omitted, the controller will take the default action, which by convention is a method in the controller called actionIndex(). If the ControllerID is also omitted, the application will use the default controller. The Yii default controller is called SiteController.

Turning back to the example, the router will analyze the URL, http://yourblog.com/post/show/id/99, and take the first part of the URL path post to be the ControllerID and the second part show to be the ActionID. This will translate to routing the request to the actionShow() method within the PostController class. The last part of the URL, the id/99 part, is a name/value querystring parameter that will be available to the method during processing. In this example, the number 99 represents the unique internal ID for the selected blog post.

In our fictitious blog application, the actionShow() method handles requests for specific blog post entries. It uses the querystring variable id to determine which specific post is being requested. It asks the model to retrieve information about blog post entry number 99. The model AR class interacts with the database to retrieve the requested data. After retrieving the data from the model, our controller further prepares it for display by making it available to the view. The view is then responsible for handling the data layout and providing a response back to the browser for user display.

This MVC architecture allows us to separate our data presentation from our data manipulation, validation, and other application business logic. This makes it very easy for developers to change aspects of the application without affecting the UI, and for UI designers to freely make changes without affecting the model or business logic. This separation also makes it very easy to provide multiple presentations of the same model code. For example, you could use the same model code that drives the HTML layout of http://yourblog.com to drive an RIA presentation, a mobile application, web services, or a command-line interface. In the end, following these set conventions and separating the functionality will result in an application that is much easier to extend and maintain.

Yii does a lot more to help you enforce this separation, than simply providing some naming conventions and suggestions for where your code should be placed. It helps to take care of all the lower-level, "glue" code needed to stitch all the pieces together. This allows you to reap the benefits of a strict MVC designed application without having to spend all the time in coding the details yourself. Let's take a look at some of these lower-level details.


Object-relational mapping and Active Record

For the most part, the web applications we build house their data in a relational database. The blog posting application we used in the previous example holds blog post content in database tables. However, web applications need the data that is held in the persistent database storage to be mapped to in-memory class properties that define the domain objects. Object-relational mapping (ORM) libraries provide this mapping of database tables to domain object classes.

Much of the code that deals with ORM is about describing how fields in the database correspond to properties in our in-memory objects, and is tedious and repetitive to write. Luckily, Yii comes to the rescue and saves us from this repetition and tedium by providing an ORM layer in the form of the Active Record (AR) pattern.

Active Record

As previously mentioned, AR is a design pattern used to abstract database access in an object-oriented fashion. It maps tables to classes, rows to objects, and columns to class properties. In other words, each instance of an Active Record class represents a single row in a database table. However, an AR class is more than just a set of attributes that are mapped to columns in a database table. It also houses the necessary business logic to be applied to that data. The end result is a class that defines everything about how it should be written to and read from the database.

By relying on convention and sticking with reasonable defaults, Yii's implementation of AR will save the developer a ton of time that might otherwise be spent in configuration, or in writing the tedious and repetitive SQL statements required to create, read, update, and delete data. It also allows the developer to access data stored in the database in an object-oriented manner. To illustrate this, let's take our fictitious blog example once again. The following is some example code that uses AR to operate on a specific blog posting, whose internal ID, which is also used as the table's primary key, is 99. It first retrieves the posting by using the primary key. It then changes the title and updates the database to save the changes:

$post->title='Some new title';

Active Record completely relieves us of the tedium of having to write any SQL code or to otherwise deal with the underlying database.

In fact, active record in Yii does even more than this. It integrates seamlessly with many other aspects of the Yii framework. There are many "active" HTML helper input form fields that tie directly to their respective AR class attributes. In this way, AR extracts the input form field values directly into the model. It also supports sophisticated, automated data validation, and if the validation fails, the Yii view classes easily display the validation errors to the end user. We will be revisiting AR and providing concrete examples many times throughout this book.


The view and controller

The view and the controller are very close cousins. The controller makes available the data for display to the view, and the view generates pages that trigger events that send data to the controller.

In Yii, a view file belongs to the controller class that rendered it. In this way, we can access the controller instance by simply referring to $this inside a view script. This implementation makes the view and controller very intimate indeed.

When it comes to Yii controllers, there is a lot more to the story than just calling the model and rendering views. Controllers can manage services to provide sophisticated pre and postprocessing on requests, implement basic access control rules to limit access to certain actions, manage application-wide layout and nested layout file rendering, manage pagination of data, and many other behind-the-scenes services. Again, we have Yii to thank for not having to get our hands dirty with these messy details.

There is a lot to Yii. The best way to explore all its beauty is to start using it. Now that we have some of the very basic ideas and terminology under our belt, we are in a great position to do just that.



In this chapter, we were introduced at a very high-level to the Yii PHP Web application framework. We also covered a number of software design concepts embraced by Yii. Don't worry if the abstract nature of this initial discussion was a tad lost on you. It will all make sense once we dive into specific examples. But to recap, we specifically covered:

  • The importance and utility of application development frameworks

  • What Yii is and the characteristics of Yii that make it incredibly powerful and useful

  • MVC application architecture and the implementation of this architecture in Yii

  • A typical Yii web request life cycle and URL structure

  • Object-relational mapping and Active Record in Yii

In the next chapter, we will go through the simple Yii installation process and start building a working application to better illustrate all of these ideas.

About the 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

(1 reviews total)
Book Title
Access this book, plus 7,500 other titles for FREE
Access now