search
HomeBackend DevelopmentPHP Tutorialyii2 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

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
yii2 怎么去掉jqueryyii2 怎么去掉jqueryFeb 17, 2023 am 09:55 AM

yii2去掉jquery的方法:1、编辑AppAsset.php文件,注释掉变量$depends里的“yii\web\YiiAsset”值;2、编辑main.php文件,在字段“components”下面添加配置为“'yii\web\JqueryAsset' => ['js' => [],'sourcePath' => null,],”即可去掉jquery脚本。

手把手教你uniapp和小程序分包(图文)手把手教你uniapp和小程序分包(图文)Jul 22, 2022 pm 04:55 PM

本篇文章给大家带来了关于uniapp跨域的相关知识,其中介绍了uniapp和小程序分包的相关问题,每个使用分包小程序必定含有一个主包。所谓的主包,即放置默认启动页面/TabBar 页面,以及一些所有分包都需用到公共资源/JS 脚本;而分包则是根据开发者的配置进行划分,希望对大家有帮助。

MySQL表设计实战:创建一个电商订单表和商品评论表MySQL表设计实战:创建一个电商订单表和商品评论表Jul 03, 2023 am 08:07 AM

MySQL表设计实战:创建一个电商订单表和商品评论表在电商平台的数据库中,订单表和商品评论表是两个非常重要的表格。本文将介绍如何使用MySQL来设计和创建这两个表格,并给出代码示例。一、订单表的设计与创建订单表用于存储用户的购买信息,包括订单号、用户ID、商品ID、购买数量、订单状态等字段。首先,我们需要创建一个名为"order"的表格,使用CREATET

Java开发实战:集成七牛云云存储服务实现文件上传Java开发实战:集成七牛云云存储服务实现文件上传Jul 06, 2023 pm 06:22 PM

Java开发实战:集成七牛云云存储服务实现文件上传引言随着云计算和云存储的发展,越来越多的应用程序需要将文件上传至云端进行存储和管理。云存储服务的优势在于高可靠性、可扩展性和灵活性。本文将介绍如何使用Java语言开发,集成七牛云云存储服务,实现文件上传功能。七牛云简介七牛云是国内领先的云存储服务提供商,其提供了全面的云存储和内容分发服务。用户可以通过七牛云提

深入学习 Elasticsearch 查询语法与实战深入学习 Elasticsearch 查询语法与实战Oct 03, 2023 am 08:42 AM

深入学习Elasticsearch查询语法与实战引言:Elasticsearch是一款基于Lucene的开源搜索引擎,主要用于分布式搜索与分析,广泛应用于大规模数据的全文搜索、日志分析、推荐系统等场景。在使用Elasticsearch进行数据查询时,灵活运用查询语法是提高查询效率的关键。本文将深入探讨Elasticsearch查询语法,并结合实际案例给出

Vue实战:日期选择器组件开发Vue实战:日期选择器组件开发Nov 24, 2023 am 09:03 AM

Vue实战:日期选择器组件开发引言:日期选择器是在日常开发中经常用到的一个组件,它可以方便地选择日期,并提供各种配置选项。本文将介绍如何使用Vue框架来开发一个简单的日期选择器组件,并提供具体的代码示例。一、需求分析在开始开发之前,我们需要进行需求分析,明确组件的功能和特性。根据常见的日期选择器组件功能,我们需要实现以下几个功能点:基础功能:能够选择日期,并

精选几道CTF习题,带你学习yii2框架!精选几道CTF习题,带你学习yii2框架!Feb 23, 2022 am 10:33 AM

本篇文章带大家了解yii2框架,分享几道CTF习题,通过它们来学习yii2框架,希望对大家有所帮助。

MySQL表设计实战:创建一个电影信息表和演员表MySQL表设计实战:创建一个电影信息表和演员表Jul 01, 2023 pm 08:16 PM

MySQL表设计实战:创建一个电影信息表和演员表导语:在数据库设计中,表的创建是一个非常关键的环节。本文将以电影信息表和演员表为例,详细介绍如何进行MySQL表的设计和创建,并附上相应的代码示例。一、电影信息表设计和创建电影信息表是用来存储电影的相关信息,包括电影名称、导演、上映时间、电影类型等字段。下面是电影信息表的设计和创建过程,首先我们需要选择合适的字

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software