Home >Backend Development >PHP Tutorial >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_PHP Tutorial

WBOY
WBOYOriginal
2016-07-12 08:50:21992browse

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1133415.htmlTechArticleyii2 Practical Tutorial Novice Getting Started Guide - Simple Blog Management System, yii2 Novice Getting Started 1. Introduction Quick Start Guide A basic introduction to the Yii2 framework, including database migration, gii operations...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn