Home > Article > PHP Framework > 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:
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 'This is member index'; exit(); } public function actionTest(){ echo 'TTTTTTTTTTTTTTT'; exit(); } public function actionHello(){ return 'Hello World!!!'; 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
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!