Yii Framework: A Guide to Quickly Building Efficient CRUD Applications
Yii is a high-performance PHP framework known for its speed, security, and good support for Web 2.0 applications. It follows the principle of "convention over configuration", which means that much less code can be written than other frameworks (less code means fewer bugs) as long as it follows its specifications. In addition, Yii also provides many convenient features out of the box, such as scaffolding, data access objects, themes, access control, cache, and more. This article will introduce the basics of using Yii to create a CRUD system.
Key Points
- Yii is a high-performance framework suitable for Web 2.0 applications and provides many convenient features such as scaffolding, data access objects, themes, access control and caching. It follows the principle of conventions over configuration, reducing the amount of code, thereby reducing the possibility of bugs.
- Yii's command line tool
yiic
is used to create skeleton applications with appropriate directory structure. Yii follows the MVC and OOP principles, and the URL structure ishttp://localhost/yiitest/index.php?r=controllerID/actionID
. The controller and the method to be called are determined based on the ID in the URL. - Yii's web-based tool is used to generate models, controllers, and forms for CRUD operations, so as to quickly develop CRUD systems. For example, a simple system where users can perform CRUD operations on blog posts can be developed in minutes.
gii
Beginner
Suppose you have Apache, PHP (5.1 or later) and MySQL installed on your system, so the first step is to download the framework file. Visit Yii's official website and download the latest stable version (1.1.13 at the time of writing). Unzip the ZIP file to get the folder (the version identifier may vary depending on the version you downloaded), rename it to yii-1.1.13.e9e4a0
, and move it to your web-accessible root directory. In my system, this is yii
, so the path to the framework file will be C:\wamp\www
. In this article, I'll call it C:\wamp\www\yii
so that you can easily follow the action even if your settings are different. Next, we should check which features of Yii will be supported by our system. Visit <yiiroot></yiiroot>
in your browser to view the requirements details of the framework. Since we will use a MySQL database, you should enable the MYSQL PDO extension. http://localhost/yii/requirements/
Continue to move forward
Each web application has a directory structure, and Yii application also needs to maintain a hierarchical structure within the web root directory. To create a skeleton application using the appropriate directory structure, we can use Yii's command line tool yiic
. Navigate to the web root directory and type the following:
<yiiroot>/framework/yiic webapp yiitest
This will create a skeleton application called yiitest
with the minimum required files. In it you will find index.php
, which is used as an entry script; it accepts user requests and decides which controller should handle the request. Yii is based on MVC and OOP principles, so you should be familiar with these topics. If you are not familiar with MVC, please read the SitePoint series article "MVC Mode and PHP", which provides a great introduction. The Yii URL looks like http://localhost/yiitest/index.php?r=controllerID/actionID
. For example, in a blog system, the URL might be http://localhost/yiitest/index.php?r=post/create
. post
is the controller ID, create
is the operation ID. The entry script determines which controller and method to call based on the ID. The controller with ID post
must be named PostController
(ID removes the suffix "Controller" from the class name and converts the first letter to lowercase). The operation ID is the ID of the method in the controller that exists in a similar way; in PostController
, there will be a method called actionCreate()
. There may be multiple views associated with the controller, so we save the view file in the protected/views/*controllerID*
folder. We can create a view file named create.php
for our controller in the above directory and then just write the following code to present this view to the user:
public function actionCreate() { $this->render('create'); }
If necessary, other data can also be passed to the view. The operation is as follows:
$this->render('create', array('data' => $data_item));
In the view file, we can access the data through the $data
variable. The view can also access $this
, which points to the controller instance that renders it. Also, if you want a user-friendly URL, you can uncomment the following in protected/config/main.php
:
'urlManager'=>array( 'urlFormat'=>'path', 'rules'=>array( '<w>/<d>'=>'<controller>/view', '<w>/<w>/<d>'=>'<controller>/<action>', '<w>/<w>'=>'<controller>/<action>', ) )
Then the URL will look like http://localhost/yiitest/controllerID/actionID
.
Develop CRUD Application
Now that you have learned the important Yii conventions, it's time to start using CRUD. In this section, we will develop a simple system where users can perform CRUD operations (create, retrieve, update, and delete) on blog posts.
Step 1
Create a MySQL database yiitest
and create a table called posts
in it. For the purposes of this article, the table will have only 3 columns: id, title, and content.
CREATE TABLE posts ( id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, title VARCHAR(100), content TEXT )
Open the application's configuration file (protected/config/main.php
) and uncomment the following:
'db'=>array( 'connectionString' => 'mysql:host=localhost;dbname=yiitest', 'emulatePrepare' => true, 'username' => 'root', 'password' => '', 'charset' => 'utf8', )
Replace testdrive
with our database name, i.e. yiitest
. Obviously, you should also provide the credentials you need for the Yii connection.
Step 2
In Yii, each database table should have a model class of the corresponding type CActiveRecord
. The advantage is that we don't have to process database tables directly. Instead, we can use model objects corresponding to different rows of the table. For example, the Post
class is a model of the posts
table. An object of this class represents a row from the posts
table and has attributes representing the column value. To quickly generate the model, we will use Yii's web-based tool gii
. This tool can be used to generate models, controllers, and forms for CRUD operations. To use gii
in your project, find the following in the application's configuration file and uncomment it and add a password.
<yiiroot>/framework/yiic webapp yiitest
Then use the following URL to access gii
: http://localhost/yiitest/index.php?r=gii
. If you are using a user-friendly URL, the URL is: http://localhost/yiitest/gii
. Click Model Builder. gii
You will be asked for the table name; enter "posts" for the table name and use the name "Post" for the model. Then click Generate to create the model.
Checkprotected/models
, where you will find the file Post.php
.
Step 3
Now click on CRUD generator. Enter the model name as "Post". The controller ID will be automatically populated as "post". This means that a new controller will be generated under the PostController.php
name. Click Generate. This process will generate the controller and several view files for CRUD operations.
Now you have a brand new CRUD application! Click the "Try Now" link to test it. To manage posts, you need to log in as admin/admin
. To create a new post you need to visit http://localhost/yiitest/post/create
, to update a specific post, just point your browser to http://localhost/yiitest/post/update/postID
. Again, you can list all posts and delete some or all of them.
Conclusion
Yii is very powerful in developing Web 2.0 projects. In fact, we just saw how easy it is to create a fully functional CRUD system in just a few minutes! Obviously, Yii can save you a lot of work because you don't have to start from scratch. Yii provides us with the foundation we can expand as needed.
(The subsequent FAQ part is too long, it is recommended to organize it into a separate document.)
The above is the detailed content of PHP Master | Build a CRUD App with Yii in Minutes. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

The method of installing PHP varies from operating system to operating system. The following are the specific steps: 1. Windows users can use XAMPP to install packages or manually configure them, download XAMPP and install them, select PHP components or add PHP to environment variables; 2. macOS users can install PHP through Homebrew, run the corresponding command to install and configure the Apache server; 3. Linux users (Ubuntu/Debian) can use the APT package manager to update the source and install PHP and common extensions, and verify whether the installation is successful by creating a test file.

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

To completely destroy a session in PHP, you must first call session_start() to start the session, and then call session_destroy() to delete all session data. 1. First use session_start() to ensure that the session has started; 2. Then call session_destroy() to clear the session data; 3. Optional but recommended: manually unset$_SESSION array to clear global variables; 4. At the same time, delete session cookies to prevent the user from retaining the session state; 5. Finally, pay attention to redirecting the user after destruction, and avoid reusing the session variables immediately, otherwise the session needs to be restarted. Doing this will ensure that the user completely exits the system without leaving any residual information.

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.
