Home  >  Article  >  Backend Development  >  How to use Yii4 framework in php?

How to use Yii4 framework in php?

王林
王林Original
2023-05-31 17:01:381164browse

With the development of the Internet, there are more and more web development frameworks. The Yii4 framework is very popular as a high-performance, safe and easy-to-use PHP framework. This article will introduce how to use the Yii4 framework for web development.

  1. Environment configuration

First, we need to ensure that PHP, Composer and Yii4 framework are installed in the local environment. It can be installed via the following command:

Install Composer

php -r "readfile('https://getcomposer.org/installer');" | php

Install Yii4 framework

composer create-project --prefer-dist yiisoft/yii-project-template myapp
  1. Create Yii4 project

In the command line Enter the directory of the web server and use the following command to create a Yii4 project named myapp:

composer create-project --prefer-dist yiisoft/yii-project-template myapp

After the creation is completed, enter http://localhost/myapp/web in the browser to start using the local Web The server runs your application.

  1. Configuring database

The Yii4 framework supports a variety of databases, including MySQL, PostgreSQL, SQLite, etc. In the project, we need to connect to the database, which we can set in the configuration file.

Open the myapp/config/databases.php file and modify the relevant configuration according to your needs:

return [
    'driver' => 'mysql',
    'host' => 'localhost',
    'database' => 'database_name',
    'username' => 'username',
    'password' => 'password',
];
  1. Create a controller

In the Yii4 framework , the controller is used to handle requests and responses. A controller can be created using the following command:

./yii g/controller Site

This will create the SiteController.php file in the myapp/controllers directory.

namespace appcontrollers;

use yiiwebController;

class SiteController extends Controller
{
    public function actionIndex()
    {
        return $this->render('index');
    }
}
  1. Creating Views

Views are used to present data and interact with users. You can create a view using the following command:

./yii g/view site/index

This will create a view file named index in the myapp/views/site directory.

In the index view, we can write code to present data and interact with users just like we write HTML. For example:

<h1>Welcome to my Yii4 Application</h1>

<p>This is the index page of your application. You may modify the following file to customize its content:</p>

<ul>
    <li><code><?= __FILE__; ?></code></li>
</ul>
  1. Create model

Model is used to define data, data types, business rules and relationships. In the Yii4 framework, you can create a model using the following command:

./yii g/model Post

This will create a model called Post where we can define data structures, for example:

namespace appmodels;

use yiidbActiveRecord;

class Post extends ActiveRecord
{
    public static function tableName()
    {
        return '{{%posts}}';
    }

    public function rules()
    {
        return [
            [['title', 'content'], 'required'],
            [['title'], 'string', 'max' => 255],
            [['content'], 'string'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'title' => 'Title',
            'content' => 'Content',
        ];
    }
}
  1. Database Migration

Database migration is a way to maintain the structure of your database so that it can be upgraded and maintained across different development environments and production servers. In the Yii4 framework, we can create a data table using the following command:

./yii migrate/create create_post_table

This will create a migration file in the myapp/migrations directory, where we can define the structure and indexes of the data table:

use yiidbMigration;

class m210705_040101_create_post_table extends Migration
{
    public function safeUp()
    {
        $this->createTable('{{%posts}}', [
            'id' => $this->primaryKey(),
            'title' => $this->string()->notNull(),
            'content' => $this->text()->notNull(),
            'created_at' => $this->dateTime()->notNull(),
            'updated_at' => $this->dateTime(),
        ]);
    }

    public function safeDown()
    {
        $this->dropTable('{{%posts}}');
    }
}

Then, we can use the following command to run the migration:

./yii migrate
  1. Database operation

In the Yii4 framework, you can use ActiveRecord to perform data addition, deletion, modification and query operations. . For example, to query all Post data in the controller, you can write like this:

namespace appcontrollers;

use appmodelsPost;
use yiiwebController;

class SiteController extends Controller
{
    public function actionIndex()
    {
        $models = Post::find()->all();
        return $this->render('index', [
            'models' => $models,
        ]);
    }
}

In the view, you can use a list to present the query results:

<?php foreach ($models as $model) : ?>
    <div class="post">
        <h2><?= $model->title ?></h2>
        <p><?= $model->content ?></p>
    </div>
<?php endforeach; ?>

The above is how to use the Yii4 framework for web development basic process. Through the above steps, you can quickly build a basic web application, and the structure and implementation of the code are also very clear.

The above is the detailed content of How to use Yii4 framework in php?. For more information, please follow other related articles on the PHP Chinese website!

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