Creating Models, Views, and Controllers in Yii

November 7, 2009
The Yii Book If you like my writing on the Yii framework, you'll love "The Yii Book"!
This entry is part 5 of 8 in the series Learning the Yii Framework

This is the fifth post in my series on Yii, my favorite PHP framework. [intlink id=”473″ type=”post”]In the first[/intlink], I show how to download and test the framework itself. [intlink id=”563″ type=”post”]In the second[/intlink], I show how to create a basic Web application.[intlink id=”583″ type=”post”] In the third[/intlink], I walk through some configuration options. [intlink id=”607″ type=”post”]In the fourth[/intlink], I explain the database design to be used by the sample application that this and the subsequent posts discuss. In this post, I show how to use Yii’s Gii tool to create Models, Views, and Controllers in your Yii application. This post does assume you have an existing application to work with, most likely by following the steps in my previous posts.

(Note: In October 2010, I’ve updated this entire series to reflect changes in Yii since this series was written, and to take into account feedback provided through the comments. Some outdated material will be crossed out, but left in to reflect how things have changed since the series was begun in June 2009. This post had the heaviest revisions, as the command-line tools were replaced by the Web-based Gii.)

Yii, like Ruby on Rails and a few other frameworks, has tools that will generate code, files, and directories for you. As you can imagine, this is a tremendous time saver. Yii originally offered just the command-line yiic tool for this purpose (also used to create the Web application itself). As of Yii 1.1.2, there’s now the Web-based Gii, which runs in the browser. In this post, I’ll explain how to use Gii to create the fundamental Model, View, and Controller files required by the application (subsequent posts cover how to edit the auto-generated code to suit your needs).

Note: You can still use the command-line yiic, if you prefer that environment.

This post demonstrates Gii using an employees-departments example, with the two database tables already created (see the previous post). A couple notes up front:

  • Because Gii does so much of the work for you, you really want to have your design as complete as possible. If done properly, after creating your database tables following these next steps, you won’t use Gii again for the project.
  • You must enable Gii, using the instructions [intlink id=”583″ type=”post”]in the third post[/intlink].
  • Because Gii is a powerful tool, it’s best not to enable it on a live server. Ideally you’ll enable Gii on a development server, use it, and disable it, and then later put the site online.
  • If you’ll be putting the completed application on a live server which you don’t have command-line access to, you can develop the whole thing on your local computer, then upload the generated and edited files. Again, the command-line tool is really for the initial setup.
  • The successful use of the command-line tool relies upon having a properly configured command-line version of PHP installed and used to execute the command-line script. [intlink id=”563″ type=”post”]See my notes in the second post for more.[/intlink]
  • Make sure that the two database tables exist.
  • Make sure that you’ve edited your main.php configuration file so that the Yii application can connect to the database. See the third post for more.

Tip: For extra security, Gii can be set to only work for a specific IP address (i.e., yours).

Assuming you understand all of the above and have taken the requisite steps, you should now load Gii in your browser. Assuming your site is to be found at www.example.com/index.php, the Gii tool is at www.example.com/index.php/gii/. This assumes you’re using the URL management component in Yii. If not, head to www.example.com/index.php?r=gii. You should be taken to the login screen, where you just enter the Gii password (established in the configuration file), and click Enter. Assuming you entered the correct password, you’ll see a splash page and a list of options (as links).

Gii Splash Page

Gii Splash Page

The first thing you’ll want to do is generate the Models. Click the “Model Generator” link. On the following page:

  1. Enter Employee as the Table Name.
  2. Enter Employee as the Model Class. You’ll notice that the form automatically copies the table name as the Model name.
  3. Click Preview. You’ll see a table appear at the bottom of the form, indicating the files to be generated (just one in this case).
  4. Click Generate.

Tip: To automatically model every database table, just enter * for the table name.

Generating a Model

Generating a Model

You should then see a message indicating that the code was created (you can check for the new file to confirm this). If you see an error about an inability to write the file, you’ll need to modify the permissions on the protected/models directory to allow the Web server to write there. Once this works for you, repeat the process for the Department table.

These steps generate the protected/models/Department.php and protected/models/Employee.php scripts, which you can now open and check out in your text editor or IDE. When using Yii version 1.0.10 1.1.4, the Model file had about 60 110 lines of code. I’ll get into the specific code in a subsequent post, but you’ll see methods that define validation rules for the Model, relations this Model has to others, and so forth.

Next, and this is big, create CRUD functionality. CRUD stands for Create, Retrieve, Update, and Delete. In other words, everything you’d do with database content. Click the “Crud Generator” link. On the following page:

  1. Enter Employee as the Model Class.
  2. Enter employee as the Controller ID. You’ll notice that the form automatically copies the Model Class, in lower camelcase as the controller ID. So Employee becomes employee, SomeThing would become someThing.
  3. Click Preview. You’ll see a table appear at the bottom of the form, indicating the files to be generated.
  4. Click Generate.

Tip: If you know you won’t need certain functionality, such as the ability to create or delete a Model type, deselect the corresponding checkboxes.

You should then see a message indicating that the code was created. Again, if you see an error about an inability to write the file, you’ll need to modify the permissions on the protected/controllers and protected/views directories to allow the Web server to write there. Once this works for you, repeat the process for the Department Model. The resulting page will also offer up a link to go test the generated files.

Crud Generator

Crud Generator

That one step will create the Controller file for each Model (DepartmentController.php and EmployeeController.php), plus a View directory for each, with eight View files per Model:

  • _form.php
  • _search.php
  • _view.php
  • admin.php
  • create.php
  • index.php
  • update.php
  • view.php

The form file is used to both create and update records. The search script is a custom search form. The _view.php file is a template for showing an individual record. The admin script creates a tabular listing of the Model, with links to CRUD functionality. The index script is really intended for a public listing of the records. The view script is used to show the specifics of an individual record. And the create and update files are wrappers to the form page, with appropriate headings and such.


Edit for Yii 1.0: In earlier versions of Yii, prior to 1.1, the view.php file was called show.php and index.php was called list.php. There were also fewer View files created.


Note: You will have situations where you’d have a Model for something but not want CRUD functionality, so don’t assume you always take both steps.

So that’s it! You can click “logout”, then click “webapp” to return to the home page. You can confirm that what you did worked by checking out the new directories and files or by going to a URL. Depending upon whether or not you added urlManager to the application’s configuration, the URL would be something like www.example.com/index.php/employee/ or www.example.com/index.php?r=employee. You will see that there are no employees or departments to list and also that you can’t add any new records without logging in (the default is admin/admin).

In my next post, I’ll discuss how to start editing the generated code to make the application behave more like you want it to in the real world. But thanks to Yii’s Gii tool, about 80% of the work has been done for you!