Yii framework to create your own web App

Source: Internet
Author: User
Tags php framework sqlite database sqlite manager yii

This article is reproduced from http://www.ibm.com/developerworks/cn/opensource/os-cn-yii/

Yii is the most popular PHP framework at home and abroad today. Due to its high-performance features, it is recognized as the "most efficient PHP framework". YII provides almost everything you need for today's WEB 2.0 application development. It can quickly create a code framework for a Web application through a simple command YIIC, which enables developers to quickly develop Web applications by writing their own business logic on the generated code framework. This article will illustrate the YII framework through concrete examples, so that readers can learn how to use the YII framework to create their own WEB applications in real cases, so as to have a more realistic experience of this excellent PHP framework.

Yii Framework Overview What is YII?

Yii is a high-performance, component-based PHP framework for rapid development of WEB applications.

Yii's name comes from the acronym "Yes It is". This sentence definitely answers a number of questions about the framework: "Is it fast?" Is it safe? Is it strong? Is it suitable for our project? ”

What does Yii do for you?

Yii is a general-purpose lightweight web programming framework that can be used to develop almost any Web application. With its mature caching mechanism, especially suitable for the development of high-traffic applications, such as portals, forums, Content management systems (CMS), e-commerce systems and so on.

What are the advantages of YII compared to other software?

Like most PHP frameworks, Yii is an MVC framework that separates business logic from the user interface, making it easy for developers to make changes without affecting other parts.

Yii draws on and integrates many other well-known web programming frameworks and applications at design time, maximizing the needs of Web application development. So Yii has made it stand out from many PHP frameworks, both in terms of excellent performance, rich functionality, and clear documentation.

Installation of Yii and preparation of configuration before installation

Before installing and using YII, you need to have an environment where PHP and WEB servers are installed. Currently, there are many integrated environment software that can easily implement this part of the installation. Like the wampserver we're using here. You can download and install it from Wampserver's official website. The installation of Wampserver is very simple, double-click to execute it. During the installation, it will automatically install Apache, MySQL and PHP for you, without any additional configuration, and everything is done easily and simply.

Installation of Yii

The installation of YII is more simple than you can imagine, only to perform the following two steps to start using.

One: Download Yii framework from Yii's official website

Two: Unzip the downloaded file into a folder that can be accessed by the Web

If you want to verify that the Yii installation was successful, simply enter the following URL in the browser.

http://hostname/path/to/yii/requirements/index.php

Here are the pages we see from the browser.

Figure 1. YII Installation Successful page display

How to create a Web app using Yii use the command line tool YIIC create a web App

YIIC is a command-line tool through which you can create a complete application by simply using a command.

YIIROOT/FRAMEWORK/YIIC WebApp webroot/testdrive

For example: C:\wamp\www\yii\framework>yiic.bat webapp c:\wamp\www\abc

This command automatically creates an YII code framework named ABC for you under the WWW directory. You can access this newly created app locally using the URL below.

http://localhost/abc/index.php

Is the Web app we just created

Figure 2. Web apps created with YIIC

A case study on the implementation of the test data maintenance system based on YII

We have a simple test data maintenance system to show you how to use the YII framework to quickly develop a WEB application to meet our work needs.

Let me briefly explain the basic requirements of this Web application:

This WEB application mainly realizes the maintenance and the storage of the test data, including the basic functions such as adding and deleting and checking. The test data consists of two two-dimensional tables, and two tables are "header-detail" relationships. All data is stored in a relational database to facilitate statistical queries and future extensions.

Design and preparation of the application

Functional Requirements

The most basic function is "adding and deleting". Here is the test data of the main table and the list of two tables of the operation of the increase and deletion check.

Users are required to log in with their user and record the most recently modified person and date.

Selection and design of database

Use SQLite for data storage.

SQLite is a small embedded database, small and flexible, resource-intensive, fast processing, ideal for small and medium-sized applications of data storage. Due to its outstanding performance in all aspects, more and more developers have been favored.

To create a table:

Depending on the needs of the application, we store the test data in two tables, respectively. One is the primary table, the file information is stored, and the other is the schedule, which contains the content information (PII) in the file. Between the two tables is the "header-detail" relationship.

Listing 1. Creating SQL statements for table PII and file
CREATE TABLE file (     ID INTEGER not NULL PRIMARY KEY AutoIncrement, Package     VARCHAR () is not NULL,     piifile varch AR (255) not NULL,     fileinserver varchar (255),     Comment varchar (255)  )  CREATE TABLE "PII" (     ID Integer NOT null PRIMARY KEY AutoIncrement,     Piifileid INTEGER not NULL,     piistr VARCHAR (+) NOT NULL,     CaseN o varchar Default '-',     Category VARCHAR (+),     Shipment INTEGER,     updatedat DATETIME,     ModifiedBy varchar (+),     Comment varchar (255)  )

Initialization of data:

Import data using SQLite Manager. SQLite Manager is a Firefox plugin that allows you to easily manage and maintain your SQLite database.

Organize the prepared test data into CSV, TXT and other formats and import them through SQLite Manager. Data can be quickly ready. All data is stored in the embedded database SQLite. After the application framework is established, we copy the prepared database files to the directory C:\wamp\www\pii\protected\data.

Create an application framework

In the above we mentioned "creating a Web App using the command line tool YIIC", here we show you how to create an application from the command line.

C:\wamp\www\yii\framework>yiic.bat WebApp C:\wamp\www\pii

This command automatically creates a code framework for you, a Yii named PII, under the WWW directory. You can access this newly created app locally using the URL below.

http://localhost/pii/index.php

At this point, we see 4 default tabs on the Web page: "Home", "about", "contact" and "Login". Below we will add some basic features to the page implementation.

Add basic functionality

To implement the CRUD functionality of a table

First of all, we need to implement the file information additions and deletions, that is, the data in the table file operation and maintenance.

1. Connect to the database:

Place the prepared database file Pii.sqlite in the C:\wamp\www\pii\protected\data directory.

In file C:\wamp\www\pii\protected\config\main.php, define the database files that are used.

Listing 2. Defining Database Files
' DB ' =>array (  ' connectionString ' = ' = ' SQLite: '. DirName (__file__). ' /.. /data/pii.sqlite ',      ),

2. Configuring the GII code generator

The GII is a powerful Web application code generator that can replace or simplify the workload of developers and automatically generate code to implement standard functional modules. Before we use it, we need to make some definitions of the file C:\wamp\www\pii\protected\config\main.php.

Listing 3. Configuring the GII code generator
' Import ' =>array (     ' application.models.* ',     ' application.components.* ',      ),   ' modules ' =>array ('     gii ' =>array (       ' class ' = ' System.gii.GiiModule ',       ' password ' = ' password ',        )      ,

Once defined, we can access the GII via URL http://hostname/pii/index.php?r=gii.

Figure 3. Gii code Generator

3. Modeling data sheets using the GII

In the GII, we will use model Generator to model the tables in the database. After we select Model Generator, we can see the following page.

Figure 4. Generating module code using Model Generator

Preview and generate the code, which generates the module file file.php in Protected/models.

4. Creating a CRUD code for a table

With the module files, we need to generate CRUD code for this module using the Crud Generator in the Gii.

Figure 5. Generating code using the CRUD generator

At this point, through Http://localhost/pii/index.php?r=file, you can see the file maintenance interface.

Figure 6. Generated Files Maintenance interface

Using the same method, we can also create the appropriate PHP file and maintenance page for the schedule PII.

5. Add the created functionality to the Web app

Below, we'll show you how to add the functionality you just created to your Web app. First, we need to make a little change to the file C:\wamp\www\pii_OK\protected\views\layouts\main.php.

In this file, we can customize the page that will be displayed according to our own needs. For example, looking at the code below, we made two changes: the first is to cancel the Home and contact two tab display, we added "//" commented the two lines of code. The second is the addition of two tab:files and Piis, with the addition of two lines of code that shows the two pages we created in the previous steps.

Listing 4. customizing tab pages
<div id= "MainMenu" >    <?php $this->widget (' Zii.widgets.CMenu ', Array (     ' Items ' =>array (        // Array (' label ' = ' Home ', ' url ' =>array ('/site/index ')),        Array (' label ' = ' Files ', ' url ' =>array ('/file /admin '),  //New added   Array (' label ' = ' piis ', ' url ' =>array ('/pii/admin ')),   //New added       Array (' label ' = ' about ', ' url ' =>array ('/site/page ', ' view ' = ' about '),        //Array (' label ' = ' contact ') , ' url ' =>array ('/site/contact '),        Array (' label ' = ' Login ', ' url ' =>array ('/site/login '),        ' Visible ' =>yii::app ()->user->isguest),        Array (' label ' = ' Logout '. Yii::app ()->user->name. ',        ' url ' =>array ('/site/logout '), ' visible ' =>! Yii::app ()->user->isguest))     ,    ?>  </div><!--MainMenu--

Now let's look at the effect. Sure enough, the Home and contact pages are missing, replacing them with the Files and Piis pages.

Figure 7. Added Web apps for Files and Piis

With this step, we have added the newly created two data sheet Drud application to our web page. We have been able to maintain the data in the table directly through these two pages.

Perfect function

So far, the main functionality of a WEB application for data table maintenance has been basically implemented. Of course, we often make some improvements to the existing functions according to the needs of our own use. For example, we need to make a record of the last person and date to modify the data, we need to hide some of the field's display, adjust the order in which some fields are displayed, and we may need to add some users to use the system. Since most of the code frameworks have been implemented through the GII, we only need to do some simple additions and modifications on this basis to achieve the functionality we require. Now, let's take a look at the last modified person and date modified to see how we can refine the desired functionality by modifying some code.

For example, we need to record the user and date information for the last modification of the PII data sheet. We'll first find the PHP file that maintains the Pii table. In this example, the file is C:\wamp\www\pii\protected\models\Pii.php. We add the following code at the end of the file:

Listing 5. Record modification date and user name
Public Function BeforeSave ()    {      date_default_timezone_set ("Asia/shanghai");      $this->updatedat=date (' y-m-d h:i:s ');      $this->modifiedby=yii::app ()->user->name;      return Parent::beforesave ();    }

This code sets the user name and modification date for the Updateat and ModifiedBy fields before saving the data, and then calls the BeforeSave method of the parent class. Once saved, you will find that the values of the Updated at and Modified by fields are automatically populated with the default content after you modify the PII data on the page.

Figure 8. Auto-fill Updated at and Modified by fields

Conclusion

Through this article, we learned about Yii, the most popular PHP framework today, and learned how to use the YII framework to create a WEB application by building a concrete example of a test data maintenance system. In this example, we also have a better understanding of the quick advantages of Yii in creating Web applications by using the GII code generator to automatically create a code framework for your application. We look forward to this article as a "start-up" role, in the hope that more people will understand and use the framework, and develop more and better applications.

Yii framework to create your own web App

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.