除了默认端点创建自定义端点

时间:2016-06-01 23:28:51

标签: yii yii2 yii2-advanced-app yii2-basic-app yii2-model

我正在学习本教程

http://learncooltech.com/yii2-angular-how-to-create-single-page-application-in-minutes/

我让这个教程工作,现在我可以看到GET /书籍:逐页列出所有书籍;

但是,现在我想创建一些端点,在我的控制器中我添加了一个方法测试但是我得到了404.这里是我的控制器

namespace app\controllers;

use yii\rest\ActiveController;

class BookController extends ActiveController
{
    public $modelClass = 'app\models\Book';

    public function behaviors()
    {
        return 
        \yii\helpers\ArrayHelper::merge(parent::behaviors(), [
            'corsFilter' => [
                'class' => \yii\filters\Cors::className(),
            ],
        ]);
    }


    public function actionTest(){
        return json_encode(array("name"=>"John Doe"));
    }

}

我将此作为我的urlRule

 'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                ['class' => 'yii\rest\UrlRule', 'controller' => ['book']],
            ],
        ], 

我正在做

http://localhost/events/test

到达端点

我得到了这个

<head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-param" content="_csrf">
        <meta name="csrf-token" content="cWdHTlZnWE8uNn5jEDQVHwZXJDcUIykKADUjAgM/Ei4dXn4mOAwNCg==">
        <title>Not Found (#404)</title>
        <link href="/assets/a7503887/css/bootstrap.css" rel="stylesheet">
        <link href="/css/site.css" rel="stylesheet">
    </head>
    <body>

1 个答案:

答案 0 :(得分:0)

通过将规则更改为此

来实现它
 'rules' => [
                ['class' => 'yii\rest\UrlRule', 'controller' =>
                    ['book'],
                    'extraPatterns' => [
                          'GET test' => 'test',
                ],
                ],