


yii2 Practical Tutorial - Beginner's Guide - Simple Blog Management System, yii2 Beginner's Guide_PHP Tutorial
Yii2 Practical Tutorial Beginner’s Guide - Simple Blog Management System, yii2 Beginner’s Guide
1. Introduction
The quick start guide will give a basic introduction to the Yii2 framework, including database migration, gii operations, AR models, routing, validation, views, etc. If you are new to Yii2 or even new to the PHP framework before, this will be a good starting point for you. If you have already used and mastered the basics of the Yii2 framework, you can look forward to the advanced Yii2 tutorial (I will update it later).
In order to demonstrate the basic use of Yii2 features, I will lead you to build a simple blog management system.
The complete code of this tutorial will be made public on github later.
2. Installation
We have written about the installation tutorial of the full version of Yii2 before. You can click for reference. Here we only go through the steps and no necessary explanations are given.
composer <span>global</span> <span>require</span> "fxp/composer-asset-plugin:~1.1.1"<span> composer create</span>-project yiisoft/yii2-app-advanced advanced 2.0.8<span> cd advanced php init<br /></span>
#之后构建本地环境,我们配置advanced.dev指向frontend/web目录
3. Prepare the database
When developing and maintaining a database-driven application, the structure of the database will change as the code changes. For example, during the development of the application, a new table will be added and must be added; after the application is deployed to the production environment, an index needs to be established to improve query performance, etc. Because the source code often needs to be changed when a database structure changes, Yii provides a database migration function, which can record database changes so that the database and source code are both under version control.
In this example, we use the yii migrate
command to generate the data table migration corresponding to the blog:
yii migrate/create create_blog_table
The migration file generated by this command is located in the advancedconsolemigrations directory. You may have noticed that the yii migrate command has added the primary key ID and table name to the migration file for us. Next we need to edit the file to modify the table name and add updates. More columns are listed in the data table blog:
<?<span>php </span><span>use</span><span> yii\db\Migration; </span><span>/*</span><span>* * Handles the creation for table `blog_table`. </span><span>*/</span> <span>class</span> m160525_153315_create_blog_table <span>extends</span><span> Migration { </span><span>/*</span><span>* * @inheritdoc </span><span>*/</span> <span>public</span> <span>function</span><span> up() { </span><span>$this</span>->createTable('blog',<span> [ </span>'id' => <span>$this</span>->primaryKey(), 'title' => <span>$this</span>-><span>string</span>(100)->notNull()->defaultValue(''), 'content' => <span>$this</span>->text(), 'create_time' => <span>$this</span>->datetime(),<span> ]); } </span><span>/*</span><span>* * @inheritdoc </span><span>*/</span> <span>public</span> <span>function</span><span> down() { </span><span>$this</span>->dropTable('blog'<span>); } }</span>
Before running the migration, we first configure the database and open the commonconfigmain-local.php file. We see the db configuration under components. Just refer to the following configuration
'components' =><span> [ </span>'db' =><span> [ </span>'class' => 'yii\db\Connection', <span>//</span><span> 修改host 和dbname 之前需要手动创建了dbname才可以</span> 'dsn' => 'mysql:host=localhost;dbname=advanced', <span>//</span><span>登录数据库的账号</span> 'username' => 'root', <span>//</span><span>登录数据库的密码</span> 'password' => '', 'charset' => 'utf8',<span> ]</span>, <span>//</span><span> other code</span> ],
After the database is configured, run the following command to run migrate
./yii migrate
During this period, we will be asked to confirm. Just press yes and press Enter. This command will create all the data tables defined in the migration file (consolemigrations directory) for us. After executing this command and opening the database, we will find that our blog table has been created. , which contains the columns defined in the migration.
4. Use gii to generate AR model and CRUD
gii is a module in yii2 and is a highly customizable and extensible code generation tool. Using it can greatly improve our development efficiency. Later I will also explain how to use gii to customize the templates and program codes we need. If you choose the development environment during the installation process like us, gii is turned on by default. In other words, we can use it without further configuration. You can also open the file advancedfrontendconfigmain-local.php to view the configuration code.
<span>if</span> (!<span>YII_ENV_TEST) { </span><span>//</span><span> other code</span> <span>$config</span>['bootstrap'][] = 'gii'<span>; </span><span>$config</span>['modules']['gii'] =<span> [ </span>'class' => 'yii\gii\Module',<span> ]; }</span>
Then access the gii module through the address http://advanced.dev/index.php?r=gii (at the beginning we configured advanced.dev to point to the frontend/web directory), and use its features to help us generate this A sequence of codes necessary for the operation.
4.1 Generate AR model class
Models are part of the MVC design pattern. Using models not only makes it relatively simple and convenient for us to access data, but also helps us handle complex business and logic. For more descriptions of the model, you can refer to the relevant manuals or documents. If you have any questions, you can leave a message below.
Let’s go back and click Model Generator start on the gii page to generate the AR model class as follows.
4.2 Generate CRUD code
The so-called CRUD is nothing more than Create Read Update Delete, which means create, read, update and delete. Contains basic operations for common web development. If you have just generated the Model using gii, it would be best to click CRUD Generator on the left menu to generate CRUD as shown below.
For more gii operations, you can refer to the detailed operation steps of yii2 gii.
So far, we have used gii to generate a series of model and curd operations.
Good tip: In actual development, background management should use gii to assist development, which can quickly improve development results.
Following the above operations, we will generate 9 files in the following relevant directories
common\models\Blog.<span>php common\models\BlogSearch</span>.<span>php frontend\controllers\BlogController</span>.<span>php frontend\views\blog\_form</span>.<span>php frontend\views\blog\_search</span>.<span>php frontend\views\blog\create</span>.<span>php frontend\views\blog\index</span>.<span>php frontend\views\blog\update</span>.<span>php frontend\views\blog\view</span>.php
You can then access http://advanced.dev/index.php?r=blog through routing to see the specific page information of the blog.
5. Add blog
5.1 Preparation before adding
[Considering that most domestic websites currently collect articles very frequently, and some even do not indicate the source of the original article, the original author hopes that readers can check the original article to prevent any problems and not update all articles to avoid misleading! ]
Continue reading

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

Dewu APP is currently a very popular brand shopping software, but most users do not know how to use the functions in Dewu APP. The most detailed usage tutorial guide is compiled below. Next is the Dewuduo that the editor brings to users. A summary of function usage tutorials. Interested users can come and take a look! Tutorial on how to use Dewu [2024-03-20] How to use Dewu installment purchase [2024-03-20] How to obtain Dewu coupons [2024-03-20] How to find Dewu manual customer service [2024-03-20] How to check the pickup code of Dewu [2024-03-20] Where to find Dewu purchase [2024-03-20] How to open Dewu VIP [2024-03-20] How to apply for return or exchange of Dewu

VSCode Setup in Chinese: A Complete Guide In software development, Visual Studio Code (VSCode for short) is a commonly used integrated development environment. For developers who use Chinese, setting VSCode to the Chinese interface can improve work efficiency. This article will provide you with a complete guide, detailing how to set VSCode to a Chinese interface and providing specific code examples. Step 1: Download and install the language pack. After opening VSCode, click on the left

After rain in summer, you can often see a beautiful and magical special weather scene - rainbow. This is also a rare scene that can be encountered in photography, and it is very photogenic. There are several conditions for a rainbow to appear: first, there are enough water droplets in the air, and second, the sun shines at a low angle. Therefore, it is easiest to see a rainbow in the afternoon after the rain has cleared up. However, the formation of a rainbow is greatly affected by weather, light and other conditions, so it generally only lasts for a short period of time, and the best viewing and shooting time is even shorter. So when you encounter a rainbow, how can you properly record it and photograph it with quality? 1. Look for rainbows. In addition to the conditions mentioned above, rainbows usually appear in the direction of sunlight, that is, if the sun shines from west to east, rainbows are more likely to appear in the east.

PhotoshopCS is the abbreviation of Photoshop Creative Suite. It is a software produced by Adobe and is widely used in graphic design and image processing. As a novice learning PS, let me explain to you today what software photoshopcs5 is and how to use photoshopcs5. 1. What software is photoshop cs5? Adobe Photoshop CS5 Extended is ideal for professionals in film, video and multimedia fields, graphic and web designers who use 3D and animation, and professionals in engineering and scientific fields. Render a 3D image and merge it into a 2D composite image. Edit videos easily

1. First open WeChat. 2. Click [+] in the upper right corner. 3. Click the QR code to collect payment. 4. Click the three small dots in the upper right corner. 5. Click to close the voice reminder for payment arrival.

PHP Practice: Code Example to Quickly Implement the Fibonacci Sequence The Fibonacci Sequence is a very interesting and common sequence in mathematics. It is defined as follows: the first and second numbers are 0 and 1, and from the third Starting with numbers, each number is the sum of the previous two numbers. The first few numbers in the Fibonacci sequence are 0,1,1.2,3,5,8,13,21,...and so on. In PHP, we can generate the Fibonacci sequence through recursion and iteration. Below we will show these two

With the continuous development of smart phones, the functions of mobile phones have become more and more powerful, among which the function of taking long pictures has become one of the important functions used by many users in daily life. Long screenshots can help users save a long web page, conversation record or picture at one time for easy viewing and sharing. Among many mobile phone brands, Huawei mobile phones are also one of the brands highly respected by users, and their function of cropping long pictures is also highly praised. This article will introduce you to the correct method of taking long pictures on Huawei mobile phones, as well as some expert tips to help you make better use of Huawei mobile phones.

PHP Tutorial: How to Convert Int Type to String In PHP, converting integer data to string is a common operation. This tutorial will introduce how to use PHP's built-in functions to convert the int type to a string, while providing specific code examples. Use cast: In PHP, you can use cast to convert integer data into a string. This method is very simple. You only need to add (string) before the integer data to convert it into a string. Below is a simple sample code
