Yii for beginners

You are viewing revision #31 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#96) »

  1. Intro
  2. 1. Prerequisities
  3. 2. MVC - Architecture description
  4. 3. What is it framework and why to use it
  5. 4. Yii framework
  6. 5. Using Yii in praxis
  7. 7. Used links

Intro

Hello. This is copy of my Yii Tutorial from forum:

Total fresher in PHP frameworks and Yii, I don't understand tutorials

In the forum you can ask me questions and I will try to answer them. I will also post there new PDF versions (usefull as offline version). The same content as in PDFs will be here.

Give me a few days or weeks and I will completely rewrite and reformat current version of PDF here. It can't be done in one day :-(

I'm writing this tutorial because when I was beginning with Yii I was totally lost. I didn't understand anything. I didn't know why I needed the demo project, where I should place my PHP scripts, what it means MVC, what should the folder structure look like etc. No tutorial for beginners was available.

This tutorial is meant for beginners who have never worked with any PHP framework or with Yii. Who are able to create website with standard PHP, MySQL etc., but are completely lost while beginning with Yii.

1. Prerequisities

I suppose the reader is familiar with PHP and databases (DB). He should be able to write SQL query, use DB in PHP and create at least a simple web using PHP, HTML, CSS and DB. If you don’t know anything about PHP and DB, I recommend that you stop reading and have a look at it. And what’s also important is OOP (Object oriented programming). This means classes, overriding functions, using constructor, public and private methods and properties, etc… Can be practiced in PHP, Java, C# …

2. MVC - Architecture description

First of all, we will generally look at the MVC abbreviation used above. MVC (Model-View-Controller) is a type of application architecture. It’s used in Yii framework. When your application uses MVC architecture, it is divided into 3 basic parts.

M = Model = Part that defines relations among data in DB and rules that must be followed when saving data do DB. It also gives us tools to read/save data from/to DB.

V = View = Part that is used just to show data to user. It doesn’t write to DB or count difficult things. It just receives data and shows them using HTML, CSS, JS …

C = Controller = Part that processes and changes the data, handles user’s actions, decides, counts, thinks and calls models and views … It simply acts.

MVC Schema Image 1) MVC schema

Notice the arrow directions in picture above. Controller can read/write data from/to database only via Model. Controller also evaluates user inputs, combines it with data, counts new values … and sends outputs and results to the View and DB. View formats given data and shows them. (For example draws table etc.)

As we can see, the Controller is the central point. It’s the boss. Whatever you do - Controller processes it and decides what to do next. Asks for appropriate data from DB and does what you wanted to do. We can see that Model and View don’t do anything, unless they are asked to. In some cases, Model and View do not have to be used.

So let’s focus on Controller now.

2.1. Controller

Controller is initiated whenever you enter any address in browser. When you use MVC architecture (in Yii framework), addresses have special format. They include parameter that specifies which controller will be used.

Yes, you can have more controllers. Each controller can be used to work in different part of your web. One controller can work with user accounts, another one with products you sell etc. And what does the web address look like when you use MVC?

www.myweb.com/index.php?r=myController

Parameter “r” says that you want to use Controller named “myController”. And here we can see another speciality of MVC (or Yii). Addresses contain only index.php. No other files. All the navigation is done by the “r” parameter and controllers.

2.1.1. Action

Controller can have one or more sub-controllers. Each does something else. If our controller edits users than his one sub-controller can delete users, another one can add users, third one changes them … These sub-controllers are called Actions. You can (have to) specify action using the “r” parameter. As we saw above, controller was specified like this: “?r=myController”. If our controller had action called “myAction”, and if we wanted to run it, we would write this address:

www.myweb.com/index.php?r=myController/myAction

We can rewrite this address for example like this:

www.myweb.com/index.php?r=users/edit

If you do not specify action and run only controller like this “?r=myController” than the default action will be run. The default action has to be specified in the controller using function actionIndex().

2.2. Model

Model is very simple thing in Yii. You don’t have to write a single line of its code, it can be created automatically using command line. Each table in DB has its own model. This model has the same (or similar) name like the table. Each model has 2 important functions. Find data and Save data. That’s all we usually need. When you need to read data from DB to controller you just write something like:

ModelName.FindAll() 

and that’s it. No SQL queries, no fetching array (as you would have to do in PHP). That’s the advantage of Yii and its object-oriented access to DB. When you want to write to table, the command looks cca like this:

ModelName.column = value; 
…  
ModelName.Save()

That’s it again.

Another thing that the Model provides is relations. These relations enable you to “tunnel” through one table to another. Important are Foreign Keys. Relation is something like SQL Join. When every employee has in its table the ID of his department, you can easily get info about this department by writing something like this:

$employee->department->departmentName

Where $employee is 1 particular employee selected by some criteria, the word department is name of the relation (leading from model of employees to model of departments) and departmentName is columns in table of departments.

2.3. View

As I wrote above, view has no intelligence. It just receives data from Controller and shows them. This is the only place where we use HTML, CSS, JavaScripts etc. We of course can use FORs, WHILEs, Ifs, models … But the only aim is to show data to user.

Correction: Described View is an ideal view. In praxis it’s sometimes easier not to send data from Controller to it, but to read data from DB in View (using model) and show then.

3. What is it framework and why to use it

In a shortcut. Framework is a set of functions that can ease your work. Functions are usually grouped into Classes. One example for all. In Yii framework there is available class named CHtml. It’s obvious, that it provides functions for creating HTML code. (Tables, lists, forms...). You don’t have to use HTML and solve its validity. You just call function

echo CHtml::beginForm();

and it creates this html code:

<form method=”post” action=”thisScriptName”>

And why to use frameworks? It makes your work easier. You don’t have to program every single detail, framework does something for you automatically. Yii for example integrates form-validation functions, it handles user logging and much more. You just have to discover its possibilities and learn to work with them. But it’s the hardest thing. (Sometimes it’s faster to create your own function than to try to understand a prepared solution) And that’s why I write this manual. To show some possibilities in one place and in praxis so you won’t have to google the basics.

4. Yii framework

Yii framework has its web and documentation. All you need to do (if you want to use it) is to download and extract it to your localhost-folder. You of course need a PHP and MySQL server (I use WAMP. If you want to try it, turn off Skype for the moment when Wamp is starting. Otherwise it won’t start.)

4.1. The demo project and folder structure

Now you have Yii “installed” (= you copied all files to localhost-folder). And what next? It may look useless now… The best way to become a friend with Yii is to try the Demo project, go through it and look what it’s code looks like. Every manual describes it, but doesn’t explain why you should use the Demo project. I didn’t understand why everybody was pushing me into some boring demo project, while I wanted to do a real one.

The demo project is good because you will see the folder structure, which is important. When you walk through the code and files, you will understand how you can send data from Controller to View or how forms are validated. You will see how works navigation using the “r” parameter etc.

These: Hello World, First project and Blog could help you. Manuals describe basic work with Yii like creating demo project, relations among tables etc …

In demo project (as same as in any other Yii project) is important folder "protected". It contains 3 subfolders: models, controllers, views. There are stored PHP scripts that power your web.

Models

  • You will find there only 2 "fictive" models. I say "fictive" because they are not connected to DB. Demo project does not work with DB at all. These models are more like a definition of logics for HTML forms. When a HTML form is confirmed on webpage, it's content is checked (validated) using rules specified in these models. The validation is done for example in actionContact(). (see bellow)
  • The validation rules are specified in rules() method.
  • Items of form are defined as properties of model class.
  • Captions for form items are in method attributeLabels().
  • There is almost no difference between "fictive" and "real" model. They look 99% the same.
  • If your model should work with database, it would not extend class CFormModel, but CActiveRecord and it would contain method tableName().

Controllers

Actually, you will see only 1 controller - SiteController.php. Open it in any text editor and have a look at methods:

  • actionIndex() - it only renders view "index"
  • actionContact() - is creates a new instance of model ContactForm, assignes it data from POST and tests them (all of this is described in next chapters) Finally it renders view "contact" and sends it variable $model as a parameter.
  • actionLogout() - you can see how to call system variables and methods of Yii and how you can redirect to a different URL.
  • These are the only important things for you in controller.

Views

You will see 2 subfolders:

  • layouts: contains mainly file main.php with definition of the whole website layout, menu items, logo etc.
  • site: contains views used in SiteController. Take a look at login.php file. This view is called from actionContact() and it receives $model as a parameter. You will see that you can start using this variable without any other definition. Just write $model.

Last important file is "protected/config/main.php". There is definition of DB connection, of your application name etc. You will add lines to this file in order to run new (hidden) functions of Yii.

Important for Windows:

To use command line commands mentioned in manuals (you need them to create the demo project and to use the best things Yii offers = mainly models and relations between them), you will have to modify the “environmental variables”. Right click “This computer” choose “Properties”, than “Advanced” tab and click on button “Environmental Variables”.

A new window with 2 list-boxes will appear. In the lower one find row with variable named “Path”. Add to its value something like this: (yii framework folder path and php path)

C:\Program Files\wamp\www\yii\framework ; C:\Program Files\wamp\bin\php\php5.3.0

5. Using Yii in praxis

Here will be examples of commonly used functions, useful tricks etc. These things are hard to be figured out just so. I will paste here everything I have discovered so far.

5.1. Create demo project and set it up

If you are a rookie, first of all, you should create the demo project, set connection to your DB [7] and understand how it works. When you already are a friend with Yii, you could be able to create folder structure just by yourself.

5.2. Create Databse for your project

Very important thing is database. You should design it first. Before writing any code. When this is done, you will use command line to generate part of your application automatically. Command line can generate models, views and controllers. (I generate only models because I want to make it my way)

See this. It’s 4th part of a Yii tutorial [8].

In this tutorial [8] is said, how you should name tables and columns to be able to generate relations among tables automatically. But names are not so important. More useful is to declare relations in DB when designing it. If you use PhpMyAdmin, just create a table with foreign keys (FKs) and go to the “Structure” tab and under the list of columns you will find link to relations creation. When you click it a new screen appears and you can set foreign keys (FKs) relations. Or use software mentioned bellow to design whole DB (I recommend). When SQL relations are defined, Yii’s console will recognize them and will automatically create relations among Models. Otherwise you would have to declare these relations manually. Which is not impossible, but more comfortable is to have it in DB definition.

5.2.1. DB design tool

Very interesting thing is that relations will be created automatically when you define foreign keys using SQL relations. I recommend for example software “MySQL Workbench” [10] which is freeware. It allows you to design your DB including SQL relations using graphical tool (ER diagram). You can also enter default data to your tables. It’s very comfortable mainly when you need to delete DB and create it again, or when it has to be redesigned. You see everything on one screen.

![MySQL Workbench screenshot](http://racky.wz.cz/yii_manual/imgs/workbench.gif "MySQL Workbench screenshot")

Image 2) MySQL Workbench in action - ER creation

To create relation between 2 tables, create first the tables. Then you will need only 1 button from the toolbar that’s on the left side of the screen. It’s the one on the bottom. Its caption is “Place relation using existing columns”. No other relations will be needed. Click this button and you will be asked to select FK column in any table. Select it and click the button in the black box that appeared few seconds ago. Then you click appropriate PK column in another table and you’re done with this relation.

![MySQL Workbench toolbar](http://racky.wz.cz/yii_manual/imgs/mysqlWorkbenchRelationButton.bmp "MySQL Workbench Toolbar") ![MySQL Workbench "Pick relation" msgbox](http://racky.wz.cz/yii_manual/imgs/mysqlWorkbenchRelationButton2.bmp "MySQL Workbench "Pick relation" msgbox")

When you’re done with DB design, you just export the whole DB into an SQL script and paste it to your DB editor (for example PhpMyAdmin), or in new version you can export DB directly to MySQL using shortcut Ctrl+G I think. Finally you run the command “yiic shell” and create models. Simple and quick.

I recommend that you go to menu Tools / Options and set “History size” to ca 10-30 steps. Default value is 0, which means unlimited number of undo steps. But it slows down the application very very much.

In versions released in year 2011 I noticed their instability under Win XP SP3. So be patient.

![MySQL Workbench screenshot](http://racky.wz.cz/yii_manual/imgs/workbench1.jpg "MySQL Workbench screenshot")
5.2.1. Run Yiic shell

When your DB is ready, set the DB connection in file yourProject/protected/config/main.php. Than go to your web-project folder using Command line and write command: yiic shell. It will enable the Yii console and you will be able to create model for 1 table like this: model tableName, or for all tables at once like this: model *

You can use command: “crud TableName” to generate administration for our table. Than you can, of course, change generated forms and web pages to fit your requirements.

5.2.2. Define relations in models manually

Now, when you created models for all tables, it may be necessary to define relations (if they were not generated automatically or when you need more of them). This can be done using function relations() in model file.. see the video, time 12:15 or manual [9]. What is the relation? As I wrote above, it’s an SQL Join. You specify Primary key (PK) and foreign key (FK) using these relations and Yii can then “tunnel” from Employee to his job description via Jobs FK in the Employees table. When you make relation from list of employees to their jobs and name this relation ‘job’, you can then write this in Controller to get employee’s job:

$Employee = Employees::model()->findByPk($employeeId);
$myJobName = $Employee->job->jobName;

/*
Where:
Employees = model of table created using yiic shell. 
jobName = column in Jobs table. 
job = relation name.
$Employee = 1 returned record from table Employees - only one because we were searching by PK. If we searched using findAll() it would return list of records and it would be necessary to walk through them using foreach.

In your model should be cca this function:
*/

public function relations()
{
  return array(
	           'job' => array(self::BELONGS_TO, 'JobsTableName', 'id_job'),
           );
}
/*
But I’m not sure with the BELONGS_TO. Second possibility is HAS_ONE. See links and explanations. And as I am never sure, I recommend to specify relations in DB a generate them using command line.
*/
5.3. How to create your first controller

You just need one file in folder: protected / controllers. The file must be named like this: “NameController.php”. First letter of the Name is upper case as same as the first letter of Controller. It’s necessary for Linux servers. Example. You want to create controller named “My first”. The filename will be “MyfirstController.php”. And what’s inside?

<?php
class MyfirstController extends Controller
{
		public function actionIndex()
{
… here is your code for this action …
}

public function actionMyaction()
{
… here is your code for this action …
$this->render(‘myview’);
}

public function getEmployeeName()
{}

}
?>

As you can see, controller is a Class and contains definitions of action and non-action functions. Default and important action is actionIndex(); It’s used when you don’t specify any action in “r” parameter (as mentioned above). You can add any action you want. For example “My action” as shown above. The “r” parameter of “actionMyaction” would look like this:

“?r=Myfirst/Myaction”.

What does mean the row where is written following?

$this->render(‘myview’);

It tells the action to run a view. View is the part of your application, where you use HTML, CSS formatting etc. and it’s used to show anything to user. Vide infra. (You can also try function renderPartial() – can be usefull) Yii will look for this view in folder Views/Myfirst. Where “Myfirst” is name of controller. Yes, every controller has its own set (folder) of views.

5.3.1. Controller - Notes from praxis

5.3.1.1. SESSION

In controller, you may want to use a Session so you can send data among scripts without using forms, POST or GET. (Session is a PHP term, use Google to understand) If you want to use session in Yii, you just write this: Yii::app()->session[“varName”] = $value; That’s it. Session variable will be automatically registered, session will be started, etc.

5.3.1.2. USING RELATIONS

If you use relations, you can access one table from another one using command like this:

$employees = $department->get_employees; //(get_employees = relation name)

You can also specify which employees you want to get - by DB column name:

$employees = $department->get_employees(array('condition'=>'born<1950'))

Or you can join tables and order it by any column:

$subMenuItems = MainMenu::model()->with('relation1.relation2')->findAll(array('condition'=>'id>21 and relation2.tableColumnName = 3', 'order'=>'relation1.tableColumnName'));

Explanation: Model named MainMenu has relation named “relation1” which is pointing to another model (to another table in DB). The target model has relation named “relation2” referring to a third table. Using following command we join 3 tables:

MainMenu::model()->with('relation1.relation2') 

5.3.1.3. SETTING HTML PAGE TITLE

Every action in every controller does something different. So it’s good to set page title in every action. You can do this by this command:

$this->pageTitle = ‘My page title’

If you want to use your project name in this title or anywhere else, you can use this system variable:

Yii::app()->name

It’s value is set in file: protected/config/main.php

5.4. View

View is a very simple thing so I will just show some "tricks".

5.4.1. Grouped drop down list

Html code can be generated semi-automatically using static class CHtml. You can create for example drop-down-list like this:

Instead of this:

<select name="selectName" id="selectName">
<option value="1">item1</option>
<option value="2">item2</option>
…
</select> 

You can write this:

echo CHtml::dropDownList($name, $select, $data, $htmlOptions);

• $name = name that will be used in $_POST when form is send

• $select = string with selected value

• $data = content - interesting think, see bellow

• $htmlOptions = classical array of attributes:

array('width'=>'100','style'='color:red;')
$data = CHtml::listData( Model::model()->findAll(),'id_item','item_descr' )

Method listData() just generates following array:

array(‘value1’=>’caption1’, ‘value2’=>’caption2’ … )

Explanation: $data is a set of tags. Basically it’s simple mixed Array with “name=>value” pairs. This Array can be created automatically using function:

listData($listOfItems, $valueColumn, $captionColumn)

• $listOfItems = it’s clear, you use for example: findAll(array(‘condition’=>’id>4’))

• $valueColumn = what column will be used to fill the value of tag

• $captionColumn = what column will be used to fill the caption of tag

... to be continued ...

7. Used links

[7] Configure Yii:

http://blog.dmcinsights.com/2009/11/03/configuring-yii/

[8] Tables in DB:

http://blog.dmcinsights.com/2009/11/05/creating-models-views-and-controllers-in-yii/

[9] Relations between models:

http://www.yiiframework.com/doc/guide/database.arr

[10] MySQL Workbench

[http://dev.mysql.com/downloads/workbench/5.2.html]( http://dev.mysql.com/downloads/workbench/5.2.html " http://dev.mysql.com/downloads/workbench/5.2.html")

[11]

http://www.sterlingsavvy.com/tutorials/index.php?t=1&l=10

[12] Ajax Yii documentation

http://www.yiiframework.com/doc/api/CHtml#ajax-detail

[13] Ajax Yii coockbock + discussion !

http://www.yiiframework.com/doc/cookbook/24/

[14] Mode: method rules()

http://www.yiiframework.com/doc/guide/1.1/en/form.model

[15] Active Record

[http://www.yiiframework.com/doc/guide/1.1/en/database.ar]( http://www.yiiframework.com/doc/guide/1.1/en/database.ar " http://www.yiiframework.com/doc/guide/1.1/en/database.ar")

[CDbCriteria][16] [16]:http://www.yiiframework.com/doc/api/1.1/CDbCriteria

(http://www.yiiframework.com/doc/api/1.1/CDbCriteria "http://www.yiiframework.com/doc/api/1.1/CDbCriteria")

68 0
75 followers
Viewed: 443 206 times
Version: Unknown (update)
Category: Tutorials
Written by: rackycz
Last updated by: rackycz
Created on: Oct 9, 2011
Last updated: 5 years ago
Update Article

Revisions

View all history

Related Articles