1. What is Yii?
Yii is a high-performance, component-based PHP framework for developing large-scale Web applications rapidly. It enables maximum reusability in Web programming and can significantly accelerate your Web application development process. The name Yii (pronounced Yee or [ji:]) is an acroynym for “Yes It Is!”. This is often the accurate, and most concise response to inquires from those new to Yii.
1. Requirements
To run a Yii-powered Web application, you need a Web server that supports PHP 5.1.0. For developers who want to use Yii, understanding object-oriented programming (OOP) is very helpful, because Yii is a pure OOP framework.
2. What is Yii Best for?
Yii is a generic Web programming framework that can be used for developing virtually any type of Web application. Because it is light-weight and equipped with sophisticated caching mechanisms, it is especially suited to high-traffic applications, such as portals, forums, content management systems (CMS), e-commerce systems, etc.
3. How does Yii Compare with Other Frameworks?
Like most PHP frameworks, Yii is an MVC framework. Yii excels other PHP frameworks at being efficient, feature-rich and clearly-documented. Yii is carefully designed from the ground up to be fit for serious Web application development. It is neither a byproduct of some project nor a conglomerate of third-party work. It is the result of the authors’ rich experience with Web application development and their investigation of the most popular Web programming frameworks and applications.
2. How to setup a Yii framework Environment?.
To setup Yii on your machine, we have to follow these steps:-
1.Download the Yii framework.
2.Then extract and put it in a location on you machine. And its not required to put it in the document root directory. You can put this extracted file anywhere and its should accessible from scripts.
Yii also supporting Apache and NginX web servers. For apache its ready to work with the default configuration. The .htaccess file restricting to view the restricted files from external world. The NginX web server required some more configuration than Apache configuration.
3. Features of Yii Framework:
- Model-View-Controller(MVC) design
- Database Access Objects(DAO), Query Builer and Active Record
- Form input and Validation
- SEO friendly URL management
- Automatic code generation either through GUI or CLI mode
- AJAX-enabled widgets
- Authentication and authorization
- Skinning and theming etc…
4. 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 affecting 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 implementing MVC, Yii also introduces a front-controller, called Application, which encapsulates the execution context for the processing of a request. Application collects some information about a user request and then dispatches it to an appropriate controller for further handling.
The following diagram shows the static structure of a Yii application:
Static structure of Yii application
5. How to create Your First Yii Application ?
Once we have completed the Yii framework installation, the next step is to create a Yii framework application. To give you an initial experience with Yii, in this section we describe how to create your first Yii application. We will use yiic (command line tool) to create a new Yii application and Gii (powerful web based code generator) 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/myapp
This will create a skeleton Yii application under the directory WebRoot/myapp. The application has a directory structure that is needed by most Yii applications.
And we can see the following result once we create an application:-
myapp/ 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 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 UserIdentity.php the 'UserIdentity' 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 myapp.db the sample SQLite database file extensions/ containing third-party extensions messages/ containing translated messages 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
Without writing a single line of code, we can test drive our first Yii application by accessing the following URL in a Web browser:
http://hostname/myapp/index.php
So now your basic application in Yii framework is ready to use. If you open the above link on your machine you can see the basic application, and then we have to make sure some of these directories have enough permission or not. Which are listed below:-
- WebRoot/assets
- WebRoot/protected/data
- WebRoot/protected/runtime
If we want to customize the application for our requirement we have to edit the contents in protected directory. Which is similar as the ‘app’ directory in some other frameworks.
The main areas where we have to edit in controllers, models and views. Because Yii is a pure object orineted MVC framework. The main configuration settings will be in the config directory. We can make all necessary configuration changes in the config/main.php file, like DB selection and connection, formated URL, application name, log messages display on web pages, and other configuraion settings.
We can add different modules into module directory and just make enough setting to view the changes in the application. Say an example, adding the user module, which will give a user related all things in a very user friendly way. Similar like this, there are many modules available in Yii framework.
Once we have complete all these basic level settings and configurations then we can auto-generate code either via command line or through GUI. The main thing we have with us is the database table schema. If we have the schema we can generate code through one of the above specified method.
Say an example, if we have a post table schema and once we finish generate code, it will create a file in model directory, controller directory and will create a directory named ‘post’ inside the views directory. And we can do our logical changes in the controller file names ‘PostController.php’ and if we want to edit the visual changes then we have to edit files in the views/post directory.
The views/post directory may contains the following files:-
- admin.php
- create.php
- _form.php
- index.php
- _search.php
- update.php
- _view.php
- view.php
6. Conventions
Yii favors conventions over configurations. Follow the conventions and one can create sophisticated Yii applications without writing and managing complex configurations. Of course, Yii can still be customized in nearly every aspect with configurations when needed.
Below we describe conventions that are recommended for Yii programming. For convenience, we assume that WebRoot is the directory that a Yii application is installed at.
1.URL
By default, Yii recognizes URLs with the following format:
http://hostname/index.php?r=ControllerID/ActionID
The r GET variable refers to the route that can be resolved by Yii into controller and action. If ActionID is omitted, the controller will take the default action (defined via CController::defaultAction); and if ControllerID is also omitted (or the r variable is absent), the application will use the default controller (defined via CwebApplication::defaultController).
With the help of CUrlManager, it is possible to create and recognize more SEO-friendly URLs, such as http://hostname/ControllerID/ActionID.html. This feature is covered in detail in URL Management.
2.Code
Yii recommends naming variables, functions and class types in camel case which capitalizes the first letter of each word in the name and joins them without spaces. Variable and function names should have their first word all in lower-case, in order to differentiate from class names (e.g. $basePath, runController(), LinkPager). For private class member variables, it is recommended to prefix their names with an underscore character (e.g. $_actionList).
Because namespace is not supported prior to PHP 5.3.0, it is recommended that classes be named in some unique way to avoid name conflict with third-party classes. For this reason, all Yii framework classes are prefixed with letter “C”.
3.Configuration
A configuration is an array of key-value pairs. Each key represents the name of a property of the object to be configured, and each value the corresponding property’s initial value. For example, array(‘name’=>’My application’, ‘basePath’=>’./protected’) initializes the name and basePath properties to their corresponding array values.
4.File
Conventions for naming and using files depend on their types.
Class files should be named after the public class they contain. For example, the CController class is in the CController.php file. A public class is a class that may be used by any other classes. Each class file should contain at most one public class. Private classes (classes that are only used by a single public class) may reside in the same file with the public class.
View files should be named after the view name. For example, the index view is in the index.php file. A view file is a PHP script file that contains HTML and PHP code mainly for presentational purpose.
Configuration files can be named arbitrarily. A configuration file is a PHP script whose sole purpose is to return an associative array representing the configuration.
5.Directory
Yii assumes a default set of directories used for various purposes. Each of them can be customized if needed.
- WebRoot/protected: this is the application base directory holding all security-sensitive PHP scripts and data files. Yii has a default alias named application associated with this path. This directory and everything under should be protected from being accessed by Web users. It can be customized via CWebApplication::basePath.
- WebRoot/protected/runtime: this directory holds private temporary files generated during runtime of the application. This directory must be writable by Web server process. It can be customized via CApplication::runtimePath.
- WebRoot/protected/extensions: this directory holds all third-party extensions. It can be customized via CApplication::extensionPath. Yii has a default alias named ext associated with this path.
- WebRoot/protected/modules: this directory holds all application modules, each represented as a subdirectory.
- WebRoot/protected/controllers: this directory holds all controller class files. It can be customized via CWebApplication::controllerPath.
- WebRoot/protected/views: this directory holds all view files, including controller views, layout views and system views. It can be customized via CWebApplication::viewPath.
- WebRoot/protected/views/ControllerID: this directory holds view files for a single controller class. Here ControllerID stands for the ID of the controller. It can be customized via CController::viewPath.
- WebRoot/protected/views/layouts: this directory holds all layout view files. It can be customized via CWebApplication::layoutPath.
- WebRoot/protected/views/system: this directory holds all system view files. System views are templates used in displaying exceptions and errors. It can be customized via CWebApplication::systemViewPath.
- WebRoot/assets: this directory holds published asset files. An asset file is a private file that may be published to become accessible to Web users. This directory must be writable by Web server process. It can be customized via CAssetManager::basePath.
- WebRoot/themes: this directory holds various themes that can be applied to the application. Each subdirectory represents a single theme whose name is the subdirectory name. It can be customized via CThemeManager::basePath.
6.Databases
Most Web applications are backed by some database. For best practice, we propose the following naming conventions for database tables and columns. Note that they are not required by Yii.
- Both database tables and columns are named in lower case.
- Words in a name should be separated using underscores (e.g. product_order).
- For table names, you may use either singular or plural names, but not both. For simplicity, we recommend using singular names.
- Table names may be prefixed with a common token such as tbl_. This is especially useful when the tables of an application coexist in the same database with the tables of another application. The two sets of tables can be readily separate by using different table name prefixes.
7. Code Generation using Command Line Tools
Open a command line window, and execute the commands listed as follows,
% cd WebRoot/myapp % protected/yiic shell Yii Interactive Tool v1.1 Please type 'help' for help. Type 'exit' to quit. >> model User tbl_user generate models/User.php generate fixtures/tbl_user.php generate unit/UserTest.php The following model classes are successfully generated: User If you have a 'db' database connection, you can test these models now with: $model=User::model()->find(); print_r($model); >> crud User generate UserController.php generate UserTest.php mkdir D:/myapp/protected/views/user generate create.php generate update.php generate index.php generate view.php generate admin.php generate _form.php generate _view.php Crud 'user' has been successfully created. You may access it via: http://hostname/path/to/index.php?r=user
In the above, we use the yiic shell command to interact with our skeleton application. At the prompt, we execute two sub-commands: model User tbl_user and crud User. The former generates a model class named User for the tbl_user table, while the latter analyzes the User model and generates the code implementing the corresponding CRUD operations.
Let’s enjoy our work by browsing the following URL:
http://hostname/myapp/index.php?r=user
This will display a list of user entries in the tbl_user table.