Wednesday, December 28, 2011

How to Use Model Generator (Gii Tool - Yii Code Generator)

Model Generator, generates a model class for the specified database table. In the application of Gii Tool - Model Generator you need a database to connect. Follow the steps below:

1. Create a simple MySQL database. For example I use yiicode as database name and user as table. See the attributes as follows:

Field Type Lenght/Values Exrta Primary
id int - auto_increment Yes
name varchar 60 - -
address varchar 200 - -
website varchar 100 - -
email varchar 50 - -

To make it, open http://localhost/xampp/, click on phpMyAdmin, click Databases, on the columns Create a new database typing demo, and click create. After that click on the SQL and create a user table by entering the following SQL command:
CREATE TABLE user
(
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(60) NOT NULL,
address VARCHAR(200) NOT NULL,
website VARCHAR(100) NOT NULL,
email VARCHAR(50) NOT NULL
);

2. After that you please login to Gii - http://localhost/webappname/index.php?r=gii/default/login.
Typing in the Table Name * is tbl_user and in the Model Class * is User


You can see PHP code by click Preview button and the models\User.php. This code will be automatically stored in the xampp \ htdocs \ yourappname \ protected \ models \ User.php.
After it, click the Generate button

If successful will appear in the following:
The code has been generated successfully.
Generating code using template “xampp\htdocs\yii\framework\gii\generators\model\templates\default”…
generated models\User.php
done!
That means you have successfully created a model to perform CRUD operations.
Yii Framework Tutorials

Saturday, December 10, 2011

Configuration Gii Tool (Yii Code Generator)

Gii (automatic code generation) is a Web-based code generator tool of Yii to develop a web application development productivity. Gii is implemented as a module and should be used in the Yii application. To use Gii, you have to do some Gii configuration first. The following configuration steps Gii (producer of automatic code - Code Generator):

  1. Have you open the protected / main.config.php
  2. Find the following code
    // uncomment the following to enable the Gii tool
     /*
     'gii'=>array(
      'class'=>'system.gii.GiiModule',
      'password'=>'admin',
       // If removed, Gii defaults to localhost only. Edit carefully to taste.
      'ipFilters'=>array('127.0.0.1','::1'),
     ),
     */
    ),
  3. Remove the tag comment / * and * /, so like this
    // enable Gii tool
     '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'),
     ),
    ),
  4. Change Your password in Enter Your Password Here, for example 123456
    // enable Gii tool
     'gii'=>array(
      'class'=>'system.gii.GiiModule',
      'password'=>'123456',
       // If removed, Gii defaults to localhost only. Edit carefully to taste.
      'ipFilters'=>array('127.0.0.1','::1'),
     ),
    ),
  5. Now you have to login to Gii tool by open a web browser and type the http://localhost/yiicode/index.php?r=gii/default/login Changes yiicode with your application name.
    Before login Gii (Yii Code Generator)
    After login Gii (Yii Code Generator)
Nb: Gii is mainly provided as a development tool. Therefore, it should only be installed on a development machine. Because it can generate new PHP script files in the application, we should pay sufficient attention to its security measures (e.g. password, IP filters).

Tuesday, November 8, 2011

Configuration Yii Framework to MySQL Database

By default Yii Framework to connect to SQLite database. It can take a look at webappname \ protected \ config \ main.php. Consider the following code:
*/
'db'=>array(
 'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
),
// uncomment the following to use a MySQL database
/*
'db'=>array(
 'connectionString' => 'mysql:host=localhost;dbname=testdrive',
 'emulatePrepare' => true,
 'username' => 'root',
 'password' => '',
 'charset' => 'utf8',
),
*/

In the code above shows the application to connect to SQLite database where there are no tag "comment" while in MySQL there is a tag "comment" which means the code will not be processed. We need to do is

  1. Adding a tag comment / * and * / on SQLite SQLite database that is not executed. Consider the following code:
    /*
    'db'=>array(
     'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
    ),
    */
  2. Remove the tag comment / * and * / to MySQL database and rename testdrive.db (default) with the name of your database. example yiicode_db
    // Using MySQL database
    'db'=>array(
     'connectionString' => 'mysql:host=localhost;dbname=yiicode_db',
     'emulatePrepare' => true,
     'username' => 'root',
     'password' => '',
     'charset' => 'utf8',
    ),
So the whole database connection code would look something like the following:
/*
'db'=>array(
 'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
),
*/
// Using MySQL database
'db'=>array(
 'connectionString' => 'mysql:host=localhost;dbname=yiicode_db',
 'emulatePrepare' => true,
 'username' => 'root',
 'password' => '',
 'charset' => 'utf8',
),

Tuesday, November 1, 2011

Installing Yii Framework in XAMPP

Here I will discuss the details of the installation steps Yii Framework. But before, there are some you need to prepare to install Yii:
  • Yii Framework - Download at http://www.yiiframework.com/download/
  • Web and database Server, here I am using XAMPP - Download at http://www.apachefriends.org/en/xampp.html
  • Web Browser, here I use Mozilla Firefox - Download at http://www.mozilla.org/id/firefox/new/
After you download all, let's start installing yii. Here, I use windows 7 as the operating system.

1. Install XAMPP, here I did not explain how to install it, but just to be safe when the computer error and have to reinstall, it should be installed on a drive other than C, such as drive D, E, or others. Here I installed on drive D

2. Extract yii-x.x.x.xxxxx.tar.gz that you download, then change its name to yii, and to be more easily placed in the folder XAMPP/htdocs, so that such XAMPP/htdocs/yii.

3. Open the comand line by pressing ctrl + r and type cmd

Installing Yii Framework in Xampp
Yii Web Application
Microsoft Windows [Version 6.1.7600]
Copyright 2009 Microsoft Corporation. All rights reserved
C: \ Users \ santje>

4. Typed in the comand-line d:

Microsoft Windows [Version 6.1.7600]
Copyright 2009 Microsoft Corporation. All rights reserved
C: \ Users \ santje> d:
D: \>

5. Typing again cd xampp

Microsoft Windows [Version 6.1.7600]
Copyright 2009 Microsoft Corporation. All rights reserved
C: \ Users \ santje> d:
D: \> cd xampp
D: \ xampp>

6. After that typing cd php

Microsoft Windows [Version 6.1.7600]
Copyright 2009 Microsoft Corporation. All rights reserved
C: \ Users \ santje> d:
D: \> cd xampp
D: \ xampp> cd php
D: \ xampp \ php>

7. Typing again php.exe D:\xampp\htdocs\yii\framework\yiic webapp D:\xampp\htdocs\yiicode
Description: D: \ xampp \ htdocs \ yiicode means the application will be installed on xampp - htdocs, while yiicode is the name of my application to be made

Microsoft Windows [Version 6.1.7600]
Copyright 2009 Microsoft Corporation. All rights reserved
C: \ Users \ santje> d:
D: \> cd xampp
D: \ xampp> cd php
D: \ xampp \ php>
D: \ xampp \ php> php.exe D:\xampp\yii\ framework\yiic\webapp D:\xampp\htdocs\yiicode
Create a Web application under 'D: \ xampp \ htdocs \ yiicode'? [yes: no]

8. The last typed yes and enter.
Your application has been succesfully created under D: \ xampp \ htdocs \ yiicode

9. Open xampp-control.exe click the start button on the Apache and MySQL, and then open your web browser and type localhost/yiicode. Congratulations you have successfully created your first application yii

Typical Workflow of a Yii Application

Before we go any further, let us know how to work the first Yii application when handling a user request.

Here is a typical workflow of a series of Yii application when handling user requests.
  1. User makes a request to the URL http://www.yiicode.com/index.php?r=post/show&id=1 and Web server handles the request by running the bootstrap script index.php.
  2. Bootstrap script creates an instance application and run it.
  3. Applications to get detailed information from the user requests an application component named request.
  4. The application determines the requested controller and action with the help of an application component named urlManager. In this example, the controller is a post that refers to class PostController; and actions show the true meaning is determined by the controller.
  5. Application creates an instance controller is required to further handle user requests. Show the controller determines that the action refers to a method named actionShow the controller class. Then create and run a filter (eg access control, measurement) associated with this action. The action is executed if allowed by the filter.
  6. Action to read the Post Model where the ID is 1 from the database.
  7. Action renders a view named show with the model of the Post.
  8. View to read and display the attributes of the Post model.
  9. View running multiple widgets.

Monday, October 31, 2011

Security Standards of Yii Framework

One of the excess Yii is Yii has a standard for security against many types of attacks from outside. Here is the Security Standards of Yii Framework include:

1. Cross Site Scripting prevention
Cross-site scripting or cross-site scripting Cross (also known as XSS) occurs when a web application gathers malicious data from user. Attackers will inject JavaScript, VBScript, ActiveX, HTML, or Flash into a vulnerable application to fool users of other applications and collect data from them. Yii includes HTMLPurifier products and providing lining HTMLPurifier CHtmlPurifier components. This component is able to remove all malicious code with a thoroughly audited, secure yet have a list of allowed and ensure content is filtered according to the standard.

2. Prevention of Cross-Site Request Forgery
Attacks Cross-Site Request Forgery (CSRF) or Babysitting Cross-site Request Forgery occurs when a malicious web site lead to web browser user to perform unwanted actions on a secure site. Yii implements CSRF prevention scheme to help defeat the attack-POST-based storage based on a random value in the cookie and comparing this value with the value passed via POST requests.

3. Cookie Attack Prevention
Protect cookies from being attacked is very important, as session IDs are commonly stored in a cookie. Yii implements a cookie validation scheme that prevents cookies being modified.

Sunday, October 30, 2011

Model-View-Controller (MVC) Yii Framework

Once before I have discussed a bit about Model-View-Controller (MVC) Yii Framework on the post About Yii Framework, now I will discuss more about what else is MVC and how it works.

Yii framework design pattern implements a model-view-controller (MVC), which is widely adopted in Web programming. Model-view-controller (MVC) aims to separate business logic from user interface considerations so that developers can more easily change any part without affecting the others.

Model represents the information (data) and business rules. The model is an instance of a class that CModel or decrease CModel. The model is used to store data and relevant business rules.

A model represents a single data object. Can be either a row in a database table or an html form with user input field. Every field or a data object is represented by an attribute model. Attributes have a label and can be validated against a set of rules.

Yii implements two types of model: Model record form and active. They decrease from the same base class, CModel.

A model form is an instance of CFormModel. The model form is used to store data collected from user input. This data is usually collected, used and then discarded. For example, the login page, we can use the model form to represent the username and password information provided by the user. For more information, please refer to Working with Forms

Active Record (AR) is a design pattern is used for abstracting database access in the form of object-orientation. Each object is an instance of CActiveRecord AR or a sub-class of that class, represents a single row in a database table. The fields in the row can be represented by the property on the object the AR. Detailed information on the AR can be found in Active Record.

View contains user interface elements such as text, input form. View is a PHP script that contains a particular element of the user interface. View could contain PHP code, but code is not recommended to change the data model and should remain relatively simple. In order to maintain the spirit of separation of logic and appearance, a large part of the logic should be placed in the controller instead of a model or view.

View has a name that is used to identify the script file to display when rendering. View the same name as the file name of the script of his view. For example, referring to the file view edit the script file named edit.php. To render view, call CController :: render () with the name of the view. The method will look for view files in the directory corresponding protected / views / ControllerID.

In the script view, we can access the controller using $ this instance. Furthermore, we can draw any controller to evaluate the properties $ this-> PropertyName in the view.

View is divided into 3 parts

Layout. Layout (layout) is a special view that is used to decorate the display. Usually contains the user interface which is common among some of the view. For example, a layout may contain a header and a footer and include the content view.

Widget. Widgets are istance of a class of children CWidget or CWidget. Component that is primarily intended for purposes of appearance. Widgets are usually included in the script view to produce a complex user interface and stand-alone. For example, a calendar widget can be used to prepare a calendar user interface is complex. Widget allows reusability (reuse) the better the user interface.

View System. View refers to the display system used by Yii to display errors and recording (logging) information. For example, when a user requests to a controller or action that does not exist, Yii will raise an exception that describes the error. Yii displays the exception using a particular system view.

View naming system to follow some rules. Names like errorXXX refer to the display to display the error code CHttpException with XXX. For example, if CHttpException raised with error code 404, error404 view will be displayed.

Yii provides a set of default system view that is placed under the framework / views. View-This view can be customized to create the same display file with the same name under protected / views / system.

The controller manages the communication between the model and view. A controller is an instance of the derived class CController or CController. The controller is made by the application when the user to request it. When walking, do the action that the controller is requesting that usually require a model and create the appropriate view. An action, in its simplest form is actually just a controller class method whose name starts with the word action.

The controller has a standard action. When a user requests do not specify where the action is executed, the default action to be executed. The default action is usually named as the index. The default action can be changed by setting the instance variable public, CController :: defaultAction.

About Yii Framework

Yii is one of PHP framework object-oriented programming (OOP) component-based, high-performance for the development of large-scale Web applications. Name Yii (pronounced as / i :/) stands for "Yes It Is".

This project was first developed by a master named Qiang Xue in January 2008 and at December 2008 Yii 1.0 was released to the public. And it's amazing, just a few years ago is now a Yii PHP framework that demand a lot of people.

Yii PHP framework beyond the others in terms of efficiency, feature-richness, and clarity of documentation.

Yii framework has advantages compared to other frameworks. Here are some frameworks performance comparison chart:

RPS: Request per second - APC: Advanced php caching
From picture, look Yii framework performance beyond of other PHP framework. Yii has support for caching, this is explicitly designed to work efficiently with AJAX. Yii is much faster because of using the technique of "lazy loading" extensively. For example, do not include the class file to classes used for the first time, and it did not create the object until the object is accessed for the first time. Caching is a simple and effective way to improve the performance of Web applications. By storing data in the cache relatively static and take it from the cache when needed, it can save the time required in generating the data.

Yii implements the design pattern of the model-view-controller (MVC), which aims to separate logic from user interface considerations in order to more easily change any part without affecting the others. In MVC, the model represents the information (data) and business rules; view contains user interface elements such as text, input forms, while the controller manages the communication between the model and view.

Yii also introduced a front-controller, called Applications, which encapsulates the execution context to process a request. Application to collect some information about the user request and then sends it to the appropriate controller for further handling.

To run a applications web based Yii, required web server that supports PHP 5.1.0 or later. You can download Yii for free from the official website here: http://www.yiiframework.com/download/