Yii is a highly performant PHP Object Oriented framework that helps you build web applications quickly. The way it is designed lets you focus on what makes your application unique while it takes care of the more “boring” code definition tasks. It follows the MVC pattern for a clean separation of logic from presentation and it features quite a lot of security enforcing functionality.
In this tutorial, we continue what we started last time when we installed the Yii framework on the VPS and created our first application. If you remember, we also did a bit of configuration for URL clean-up and linked a MySQL database to be used by our application.
We will now go ahead and use some of the code generation tools provided by Yii to set up a first model for our data. Then, we will generate the code for the CRUD operations. Lastly, we will take a look at how a typical Yii application workflow works. But first, let’s create a table in the database we connected last time to hold some content - let’s say pieces of news.
If you remember, the database we created is called db_tutorial. Let’s go in the command line and create a table in this database. To brush up on your SQL skills for doing this, you can check out this article on creating and using tables in MySQL and MariaDB. So we need a table called news which contains 3 columns: id (primary and auto incremented), title, and body.
You can go ahead and use this command for the table creation if you are in a hurry:
CREATE TABLE news (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, title VARCHAR(256), body TEXT);
No need to fill it up, we will use Yii to do this nicely.
CRUD are among the most common tasks a web application has to perform. Creating, reading, updating and deleting data from a database is very important and normally you have to write yourself all the functions that perform these tasks. This is where Yii becomes fun. Using Gii, a web based code generator, we can automatically create the basic CRUD code. So let’s see how it works.
To use Gii, first we need to enable it. In the same main.php file located in the protected/config folder where we’ve been making changes in the previous tutorial, you will find a block of code you need to uncomment in order to enable Gii:
/* 'gii'=>array( 'class'=>'system.gii.
GiiModule', 'password'=>'Enter Your Password Here', // If removed, Gii defaults to localhost only. Edit carefully to taste. 'ipFilters'=>array('127.0.0.1' ,'::1'), ), */
Remove the comments and specify a password that you will use to access Gii in the browser. Now, depending on where you have installed your application, you’ll need to change the ipFilters parameter as well. By default, Gii will only be accessible from localhost. So if your server is remote, the default won’t work. So while you are developing, you can set it to false and then set it back to the way it was after you are done:
Alternatively, you can set a specific IP address you know you want to allow to connect from. Save the file and go to your browser. If you have followed the steps from the previous article about the cleaner URLs, you should go to:
If not, go to:
This should prompt you for the password you just specified and on there, you should go and see the code generation options. Before generating the CRUD code though, we need a Model class for the table we created (news). So click on Model generator and follow the instructions. Basically all you have to do is fill in the table name field and press Preview. Then you can preview the code and click Generate.
If you get an error like "Unable to write the file", make sure the web server has permissions to write in the protected/models folder. To do this, first assign group ownership of the folder to the www-data group by running the following command from your terminal (do make sure you are in application root folder):
chown root:www-data protected/models
This will make the owners of the folder the root user and the www-data group. Note that Apache operates on your site as the www-data user which is part of the www-data group. Next, make sure that also the www-data group can write in that folder:
chmod 775 protected/models
So now we have a Model class for communicating with the News table. Let’s quickly generate the CRUD code for implementing the operations for the data inside it. Go back to the same URL you were before (mysite/gii) but this time choose Crud generator. In the Model class field specify the Model name we just created (News) then click Preview and Generate after. But again make sure that the folders protected/controllers and protected/views are writable by the server (see above how to do this if you don't already know).
After generating the CRUD code, you should get a success message with a link to try it out. It will take you to a page displaying the records in the news table. Since it’s empty you will not find any. On the right side though, you will see a menu with some links to create and manage news. Go ahead and play around creating, reading, updating and deleting news. In the Manage News section, you’ll even have search, sort, and filter functionality to manage the content - all "out of the box". Additionally, you can even generate controller, form, and model classes using Gii, but we will not go into that in this tutorial.
Now that we have seen how easy it is to generate the CRUD code for the data in your application, let’s understand a bit how the Yii routing of requests works. Yii implements the model-view-controller (MVC) design pattern for a nice separation of logic from presentation. Additionally, it uses a front-controller called Application which collects information about a user request and forwards it to an appropriate controller for handling. So how does it work? Without going into all the details, the following should give you a pretty clear understanding:
Considering the default URL structure without having it cleaned (as we did in the previous tutorial), let’s say a user makes a request to http://example.com/mysite/
The bootstrapping index.php script instantiates Application which helped by the urlManager component determines the requested controller and its action - which in this case are news (found in the NewsController class) and view, respectively. The Application creates an instance of the requested Controller which then executes the action (in this case actionView). In turn, the action reads the News Model with the ID of 1 from the database and displays it in a View named show (which gets embedded in a layout) for the user in the browser.
So this is it, a not so uncommon MCV pattern to route a user request. For a diagram outlining the typical workflow of a Yii application and an exact step by step description of all the processes, you can check out this page.
In this tutorial, we've seen what makes Yii such a cool PHP framework. It lets you very easily generate models, controllers, and even the regular CRUD operation functionality so you don't have to worry about writing all this code. You just have to focus on making your application do what you want it do.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Click below to sign up and get $200 of credit to try our products over 60 days!
Nice tutorial, are you going to write a new parts?
@Jonny: Part one is here: https://www.digitalocean.com/community/articles/how-to-install-and-setup-yii-php-framework-on-ubuntu-12-04
Had a look, couldn’t find Part 1
@kiash001: We do have an article on Laravel:
Nice tutorial! Please make tutorial for Laravel framework.