Home > PHP Framework > YII > body text

How to define yii controller

(*-*)浩
Release: 2019-12-04 13:33:24
Original
2590 people have browsed it

How to define yii controller

Controller is part of the MVC pattern. It is an object that inherits the yii\base\Controller class and is responsible for processing requests and generating responses. Specifically, after taking over control from the application body, the controller analyzes the request data and transmits it to the model, transmits the model results to the view, and finally generates output response information. (Recommended learning: yii framework)

Action

The controller is composed of operations, which is the most basic unit for executing end-user requests. A controller can have one or more operations.

The following example shows a controller post containing two actions, view and create:

namespace app\controllers;

use Yii;
use app\models\Post;
use yii\web\Controller;
use yii\web\NotFoundHttpException;

class PostController extends Controller
{
    public function actionView($id)
    {
        $model = Post::findOne($id);
        if ($model === null) {
            throw new NotFoundHttpException;
        }

        return $this->render('view', [
            'model' => $model,
        ]);
    }

    public function actionCreate()
    {
        $model = new Post;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
}
Copy after login

Create controller

In Web applications, the controller should inherit yii\web\Controller or its subclasses. Similarly, in console applications, the controller inherits yii\console\Controller or its subclasses.

The following code defines a site controller:

namespace app\controllers;
use yii\web\Controller;
class SiteController extends Controller
{
}
Copy after login

The above is the detailed content of How to define yii controller. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
yii
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!