Home  >  Article  >  PHP Framework  >  How to access the controller in yii2

How to access the controller in yii2

(*-*)浩
(*-*)浩Original
2019-11-05 14:28:064102browse

How to access the controller in yii2

Yii2 default controller has only one directory under the controller directory. When needed for development, you need to add a new directory under this directory, that is, under Add a secondary directory under the controller, such as controller/api/MemberController.php, and directly access /api/member/.​​ ​ (Recommended learning: yii tutorial)

This aspect of management and code modularization is neat.

For example, you need to create a new api directory under the default controllers directory. At this time, the api-related controllers are placed in the api.

The created directory structure is as shown below:

How to access the controller in yii2

The code of MemberController.php is as follows:

<?php
//注意此处的命名空间有\api (关键关键关键)
namespace app\controllers\api;
 
use Yii;
use yii\web\Controller;
 
//位于API目录下面的Member控制器
class MemberController extends Controller{
 
    //
    public function actionIndex(){
        echo &#39;This is member index&#39;;
        exit();
    }
 
     
    public function actionTest(){
        echo &#39;TTTTTTTTTTTTTTT&#39;;
        exit();
    }
 
 
    public function actionHello(){
        return &#39;Hello World!!!&#39;;
        exit();
    }
}

For the corresponding view layer that needs to be rendered, please also create the corresponding view layer under views.

There is another way to use modules. For example, in the background admin part, you can create a module to facilitate integrated management.

The same is true in yii1. It’s just that there are more namespaces in yii2. Need to be pointed out in particular (see code).

Added screenshots of my own experiments

How to access the controller in yii2

How to access the controller in yii2

The above is the detailed content of How to access the controller in yii2. 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