<<

YII Framework Dept. of IT

1.INTRODUCTION

YII is pronounced as “yee”, and stands for “Yes It Is!”. Unlike other component based PHP frameworks, YII scores way ahead in terms of RPC performance and adopts the ‘lazy-loading’ technique that increases its efficiency manifold. Other than this critical advantage of YII over other similar Frameworks, YII is written using OOP protocols and offers extensive reusability for developing web 2.0 applications.

Installation of Yii mainly involves the following two steps:

• Download Yii Framework from yiiframework.com. • Unpack the Yii release ?le to a Web-accessible directory

After installing Yii, you may want to verify that your server satisfies all the requirements of using Yii. You can do so by accessing the requirement checker script at the following URL in a Web browser: http://hostname/path/to/yii/requirements/index.

The minimum requirement by Yii is that your Web server supports PHP 5.1.0 or above. Yii has been tested with Apache HTTP server on Windows and operating systems. It may also run on other Web servers and platforms provided PHP 5 is supported.

1.1 About YII:

Yii is a high-performance PHP framework best for developing Web 2.0 applications .Yii helps Web developers build complex applications and deliver them on-time .Yii is pronounced as Yee or [ji:], and is an acroynym for "Yes It Is!". This is often the accurate, and most concise response to inquires from those new to Yii . Is it fast? ... Is it secure? ... Is it professional? ... Is it right for my next project? ... Yes, it is! Yii is a free, open-source Web application development framework written in PHP5 that promotes clean, DRY design and encourages rapid development. It works to streamline your application development and helps to ensure an extremely efficient, extensible, and maintainable end product.

M.L.Engineering College 1 YII Framework Dept. of IT

Being extremely performance optimized, Yii is a perfect choice for any sized project. However, it has been built with sophisticated, enterprise applications in mind. You have full control over the configuration from head-to-toe (presentation-to- persistence) to conform to your enterprise development guidelines. It comes packaged with tools to help test and debug your application, and has clear and comprehensive documentation .To learn more about what Yii brings to the table, check out the features section.

1.2 Why Use YII:

1. Its fast: Using the ‘lazy-loading’ technique, YII calls classes and objects only when needed and hence helps faster loading. It has a neat integration with AJAX and uses powerful layered caching support.

2. Its secure: Using OOP standards increases the reliability of YII. Its other security essentials such as input filtering, SQL injection and cross-site scripting prevention means a stronger framework for your PHP applications to work on

3. Its developer-friendly: Using the model-view-controller (MVC) paradigm, YII offers clean separation of business rules, logic and presentation.

M.L.Engineering College 2 YII Framework Dept. of IT

2. MODEL VIEW CONTROLLER (MVC)

Yii implements the model-view-controller (MVC) design pattern which is widely adopted in Web programming. MVC aims to separate business logic from user interface considerations so that developers can more easily change each part without a_ecting the other. In MVC,the model represents the information (the data) and the business rules; the view contains elements of the user interface such as text, form inputs; and the controller manages the communication between the model and the view.Besides MVC, Yii also introduces a front-controller, called application, which represents the execution context of request processing. Application resolves the user request and dispatches it to an appropriate controller for further handling. The following diagram shows the static structure of a Yii application:

M.L.Engineering College 3 YII Framework Dept. of IT

Figure: Static structure of Yii application

3. A TYPICAL WORKFLOW

M.L.Engineering College 4 YII Framework Dept. of IT

The following diagram shows a typical workflow of a Yii application when it is handling a user request.

Figure: A typical workflow of Yii application

1. A user makes a request with the URL http://www.example.com/index.php?r=post/ show&id=1 and the Web server handles the request by executing the bootstrap script index.php .

2. The bootstrap script creates an application instance and runs it.

3. The application obtains the detailed user request information from an application component named request.

4. The application determines the requested controller and action with the help of an application component named URL Manager . For this example, the controller is post

M.L.Engineering College 5 YII Framework Dept. of IT which refers to the Post Controller class; and the action is show whose actual meaning is determined by the controller.

5. The application creates an instance of the requested controller to further handle the user request. The controller determines that the action show refers to a method named action Show in the controller class. It then creates and executes filters (e.g. access control, benchmarking) associated with this action. The action is executed if it is allowed by the filters.

6. The action reads a Post model whose ID is 1 from the database.

7. The action renders a view named show with the Post model.

8. The view reads and displays the attributes of the Post model.

9. The view executes some widgets.

10. The view rendering result is embedded in a layout.

11. The action completes the view rendering and displays the result to the user.

4. CREATING AN YII APPLICATION

M.L.Engineering College 6 YII Framework Dept. of IT

For creating YII web application we use a powerful YII tool which can be used to automate code creation for certain tasks. For simply, we assume that YII root is the directory where YII is installed, and Web Root is the document root of our Web server.

1. Preparation:

After installing the YII framework, run a simple console command “% YII Root/framework/yiicwebappWebRoot/testdrive” to generate a selection Web application built with Yii, This will create a selection Yii application under the directory WebRoot/testdrive.

2. Create The Database:

While YII can virtually eliminate most respective coding tasks, you are responsible for the real creative work . This often starts with designing the whole system to be built, in terms of some database.

2A.YII generates the model classes using the built-in web-based code generator,you can turn database table definitions into model classes instantly, without writing a single line of code. The model classes will allow you to access the database tables in an object-oriented fashion.

2B.YII generates the CRUD code using the code generator, we can further generate code that implements the typical CRUD (create, read, update, delete) features for the selected database tables. The generated code is highly usable and customizable following the well-adapted MVC(Model-View-Controller) design pattern.

3. You Customize The Code To Fit Your Exact Needs:

Finally we customize the code to fit our exact needs.For example,to find the password user column on the user administration page,simply cross out the ‘password’ element shown in the user admin view file.

Creating An First YII Application:

M.L.Engineering College 7 YII Framework Dept. of IT

1. Connecting to Database 2. Implementing CRUD Operations

To get an initial experience with Yii, we describe in this section how to create our firstYii application. We will use the powerful yiic tool which can be used to automate code creation for certain tasks. For convenience, we assume that YiiRoot is the directory where Yii is installed, and WebRoot is the document root of our Web server.

Run yiic on the command line as follows: % YiiRoot/framework/yiic webapp WebRoot/testdrive This will create a skeleton Yii application under the directory WebRoot/testdrive. The application has a directory structure that is is needed by most Yii applications.Without writing a single line of code, we can test drive our _rst Yii application by accessing the following URL in a Web browser: http://hostname/testdrive/index.php As we can see, the application has four pages: the homepage, the about page, the contact page and the login page. The contact page displays a contact form that users can fill into submit their inquiries to the webmaster, and the login page allows users to be authenticated before accessing privileged contents. See the following screenshots for more details. The following diagram shows the directory structure of our application. Please see conventions for detailed explanation about this structure. testdrive/ index.php Web application entry script file index-test.php entry script file for the functional tests assets/ containing published resource files css/ containing CSS files images/ containing image files themes/ containing application themes

M.L.Engineering College 8 YII Framework Dept. of IT

Home page

M.L.Engineering College 9 YII Framework Dept. of IT

M.L.Engineering College 10 YII Framework Dept. of IT

Contact page with input errors

M.L.Engineering College 11 YII Framework Dept. of IT

Contact page with success message

Login page

M.L.Engineering College 12 YII Framework Dept. of IT

protected/ containing protected application files yiic yiic command line script for Unix/Linux yiic.bat yiic command line script for Windows yiic.php yiic command line PHP script commands/ containing customized 'yiic' commands shell/ containing customized 'yiic shell' commands components/ containing reusable user components Controller.php the base class for all controller classes Identity.php the 'Identity' class used for authentication config/ containing configuration files console.php the console application configuration main.php the Web application configuration test.php the configuration for the functional tests controllers/ containing controller class files SiteController.php the default controller class data/ containing the sample database schema.mysql.sql the DB schema for the sample MySQL database schema.sqlite.sql the DB schema for the sample SQLite database testdrive.db the sample SQLite database file extensions/ containing third-party extensions messages/ containing translated messages

M.L.Engineering College 13 YII Framework Dept. of IT models/ containing model class files LoginForm.php the form model for 'login' action ContactForm.php the form model for 'contact' action runtime/ containing temporarily generated files tests/ containing test scripts views/ containing controller view and layout files layouts/ containing layout view files main.php the base layout shared by all pages column1.php the layout for pages using a single column column2.php the layout for pages using two columns site/ containing view files for the 'site' controller pages/ containing "static" pages about.php the view for the "about" page contact.php the view for 'contact' action error.php the view for 'error' action (displaying external errors) index.php the view for 'index' action login.php the view for 'login' action

4.1 CONNECTING TO DATABASE: Most Web applications are backed by databases. Our test-drive application is not an exception. To use a database, we need to tell the application how to connect to

M.L.Engineering College 14 YII Framework Dept. of IT it. This is done in the application confiuration file WebRoot/testdrive/protected/config/main.php,highlighted as follows, return array( ...... 'components'=>array( ...... 'db'=>array( 'connectionString'=>'sqlite:protected/data/testdrive.db', ), ), ...... ); The above code instructs Yii that the application should connect to the SQLite database WebRoot/testdrive/protected/data/testdrive.db when needed. Note that the SQLite database is already included in the skeleton application that we just generated. The database contains only a single table named tbl-user: CREATE TABLE tbl-user ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, username VARCHAR(128) NOT NULL, password VARCHAR(128) NOT NULL, email VARCHAR(128) NOT NULL );

If you want to try a MySQL database instead, you may use the included MySQL schema file WebRoot/testdrive/protected/data/schema.mysql.sql to create the database. 4.2 IMPLEMENTING CRUD OPERATIONS: Now comes the fun part. We would like to implement CRUD (create, read, update and delete) operations for thetbl_user table we just created. This is also commonly needed in practical applications. Instead of taking the trouble to write the actual code, we will use Gii -- a powerful Web-based code generator. Info:

M.L.Engineering College 15 YII Framework Dept. of IT

Gii has been available since version 1.1.2. Before that, we could use the aforementioned yiictool to accomplish the same goal. For more details, please refer to Implementing CRUD Operations with yiic shell. Configuring GUI: In order to use Gii, we first need to edit the file WebRoot/testdrive/protected/config/main.php, which is known as the application configuration file: return array( ...... 'import'=>array( 'application.models.*', 'application.components.*', ),

'modules'=>array( 'gii'=>array( 'class'=>'system.gii.GiiModule', 'password'=>'pick up a password here', ), ), );

Then, visit the URL http://hostname/testdrive/index.php?r=gii. We will be prompted for a password, which should be the one that we just entered in the above application configuration.

Generating The User Model: After login, click on the link Model Generator. This will bring us to the following model generation page,

Model Generator

M.L.Engineering College 16 YII Framework Dept. of IT

In the Table Name field, enter tbl_user. In the Model Class field, enter User. Then press the Previewbutton. This will show us the new code file to be generated. Now press the Generate button. A new file namedUser.php will be generated under protected/models. As we will describe later in this guide, this User model class allows us to talk to the underlying database tbl_user table in an object-oriented fashion.

Generating The CRUD Code: After creating the model class _le, we will generate the code that implements the CRUD operations about the user data. We choose the Crud Generator in Gii, shown as follows, In the Model Class field, enter User. In the Controller ID field, enter user (in lower case). Now press thePreview button followed by the Generate button. We are done with the CRUD code generation.

Accessing The CRUD Pages:

M.L.Engineering College 17 YII Framework Dept. of IT

Let's enjoy our work by browsing the following URL:

CRUD Generator

http://hostname/testdrive/index.php?r=user

This will display a list of user entries in the tbl_user table.Click the Create User button on the page. We will be brought to the login page if we have not logged in before. After logging in, we see an input form that allows us to add a new user entry. Complete the form and click the Create button. If there is any input error, a nice error prompt will show up which prevents us from saving the input. Back on the user list page, we should see the newly added user appearing in the list.Repeat the above steps to add more users. Notice that the user list page will automatically paginate the user entries if there are too many to be displayed in one page. If we login as an administrator using admin/admin, we can view the user admin page with the following URL: http://hostname/testdrive/index.php?r=user/admin

This will show us the user entries in a nice tabular format. We can click on the table header cells to sort the corresponding columns. We can click on the buttons on each row of data to view, update or delete the corresponding row of data. We can

M.L.Engineering College 18 YII Framework Dept. of IT browse different pages. We can also filter and search to look for the data we are interested in.

All these nice features come without requiring us to write a single line of code!

User admin page

M.L.Engineering College 19 YII Framework Dept. of IT

Create new user page

M.L.Engineering College 20 YII Framework Dept. of IT

5. DEVELOPMENT WORK FLOW

Having described the fundamental concepts of Yii, we show the common workow for developing a web application using Yii. The workow assumes that we have done the requirement analysis as well as the necessary design analysis for the application. 1. Create the skeleton directory structure. The yiic tool described in Creating First Yii Application can be used to speed up this step. 2. Con_gure the application. This is done by modifying the application con_guration file. This step may also require writing some application components (e.g. the user component). 3. Create a model class for each type of data to be managed. Again, yiic can be used to automatically generate the active record class for each interested database table. 4. Create a controller class for each type of user requests. How to classify user requests depends on the actual requirement. In general, if a model class needs to be accessed by users, it should have a corresponding controller class. The yiic tool can automate this step, too. 5. Implement actions and their corresponding views. This is where the real work needs to be done. 6. Con_gure necessary action _lters in controller classes.

M.L.Engineering College 21 YII Framework Dept. of IT

7. Create themes if the theming feature is required. 8. Create translated messages if internationalization is required. 9. Spot data and views that can be cached and apply appropriate caching techniques. 10. Final tune up and deployment.

6. CREDITS

Yii incorporates many ideas and work from other well-known Web programming frameworks and

applications. Below is a short list of those from which Yii drew inspiration.

• Prado: This is the major source of ideas for Yii. Yii adopts its component- based and event-driven programming paradigm, database abstraction layers, modular application architecture, internationalization and localization, and many of its other features and patterns. • : Yii inherits its spirit of convention over configuration. Yii also referenced its implementation of the active record design pattern for its ORM layer. • jQuery: This is integrated in Yii as the foundational JavaScript framework. • : Yii referenced its filter design and plug-in architecture. • : Yii referenced its modular design and message translation scheme.

M.L.Engineering College 22 YII Framework Dept. of IT

7. FUNDAMENTALS OF YII

1.Entry Script:

Entry script is the bootstrap PHP script that handles user requests initially. It is the only PHP script that end users can directly request to execute.

2.Debug Mode:

Yii application can run in either debug or production mode according to the constant value YII DEBUG.By default, this constant value is defined as false, meaning production mode. To run in debug mode, define this constant as true before including the yii.php file.

3.Application Base Directory:

Application base directory refers to the root directory that contains all security-sensitive PHP scripts and data.By default, it is a subdirectory named protected that is located under the directory containing the entry script.

4.Controller:

M.L.Engineering College 23 YII Framework Dept. of IT

A controller is an instance of controller or its child class created by application.When a controller runs, it performs the requested action which usually brings in the needed models and renders an appropriate view.

5.Layouts:

Layout is a special view that is used to decorate views.It usually contains portions of user interface that are common among several views.

8. FEATURES OF YII

Whether you are one developer building a fairly simple Web site, or a team of distributed developers building an extremely complex Web application, using Yii is like augmenting your development team with additional experienced, professional, and efficient resources. All for free!

You can stay focused on the tasks specific to your business requirements, and let Yii provide an implementation strategy for all of the following:

• Model-View-Controller (MVC) design pattern:Yii adopts the proven MVC architecture, which allows for clean separation of concerns (SOC). • Database Access Objects (DAO), Query Builder, Active Record, DB Migration: Yii allows developers to model database data in terms of objects and avoid the tedium and complexity of writing repetitive SQL statements.

M.L.Engineering College 24 YII Framework Dept. of IT

• Form input and validation: Yii makes collecting form input extremely easy and safe. It comes with a set of validators as well as numerous helper methods and widgets to simplify the task for form input and validation. • AJAX-enabled widgets: Integrated with jQuery, Yii comes with a set of AJAX-enabled widgets, such as auto-complete input field, treeview, data grid, which enables writing highly efficient and versatile user interface extremely simple. • Authentication and authorization: Yii has built-in authentication support. It also supports authorization via hierarchical role-based access control (RBAC). • Skinning and theming: Yii implements a skinning and theming mechanism that allows you to quickly switch the outlook of a Yii-power website. • Web services: Yii supports automatic generation of complex WSDL service specifications and management of Web service request handling. • Internationalization (I18N) and localization (L10N): Yii supports message translation, date and time formatting, number formatting, and interface localization. • Layered caching scheme: Yii supports data caching, page caching, fragment caching and dynamic content. The storage medium of caching can be changed easily without touching the application code. • Error handling and logging: Errors are handled and presented more nicely, and log messages can be categorized, filtered and routed to different destinations. • Security: Yii is equipped with many security measures to help prevent your Web applications from attacks such as SQL injection, cross-site scripting (XSS), cross-site request forgery (CSRF), and cookie tampering. • Unit and functionality testing: Yii provides support for writing and running unit tests as well as functionality tests, based on PHP Unit and . • Automatic code generation: Yii provides a set of intuitive and highly extensible code generation tools that can help you quickly generate the code you need for features such as form input, CRUD. • Friendly with third-party code: Yii is carefully designed to work well with third-party code. For example, you can use code from PEAR or Zend Framework in your Yii application.

M.L.Engineering College 25 YII Framework Dept. of IT

• Detailed documentation: Every single method or property is clearly documented. A book and comprehensive tutorials are also available for you to systematically learn Yii. • Extension : Yii provides an extension library consisting of user- contributed components. This makes the above feature list never ending.

9. ADVANTAGES AND DISADVANTAGES

ADVANTAGES

• YII Framework is relatively new in contrast with other frameworks, so it posesses a risk regarding availability in know how and longer production runs with it. BUT nevertheless. • YII has a very good documentation. • It is super fast. • It gives great power with strong code controlling. • It is not only fast in performance, it is also fast in framework release. Yii core team are releasing very often with a lot of new features. • YII community is growing rapidly. • It is 100% true OOP framework.

DISADVANTAGES

M.L.Engineering College 26 YII Framework Dept. of IT

• Yii is written in approach that does not support the most innovative, modern advantages brought to PHP development world with release of PHP 5.3 and soon – PHP version 6. • Yii does not need to be installed under a web-accessible directory.An • Yii application has one entry script which is usually the only file that need to be exposed to web users. other PHP scripts including those from yii,should be protected from web access since they may being exploited for hack.

10. CONCLUSION

Yii is an open source project released under the terms of the BSD License.This means that you can use Yii for free to develop either open-source or proprietary Web applications.The latest stable version of Yii is 1.1. You may safely use this version in your production Web applications. Continued support and bug fixes for this version will be provided until December 31, 2015. If needed, we may further extend our support for this version.We are currently actively developing our next major version 2.0. Yii 2.0 will be full rebuilt on top of PHP 5.3.0+ and is aimed to become a state-of-the-art of the new generation of PHP framework.

M.L.Engineering College 27 YII Framework Dept. of IT

11.BIBLIOGRAPHY

1. ^ a b "About Yii". Retrieved 16 October 2010. 2. ^ "Yii: a high-performance framework inheriting Prado". 6 October 2008. Retrieved 22 August 2010. 3. ^ "Features of Yii". Retrieved 22 August 2010. 4. ^ "New Features". Retrieved 26 August 2010. 5. ^ a b "Download Yii Framework". Retrieved 18 January 2011. 6. ^ "Terms of the Yii Documentation". Retrieved 22 August 2010. 7. ^ "Official Logo". Retrieved 20 October 2010.

M.L.Engineering College 28