Yii2创建restful

jerry Yii2 2015年11月15日 收藏

1.继承ActiveRecord

    <?php  
      
    namespace app\controllers\Admin;  
      
    use Yii;  
    use app\models\Admin\WebAdminUser;  
    use app\models\Admin\WebAdminUserSearch;  
    use yii\rest\ActiveController;  
      
    /** 
     * WebAdminUserController implements the CRUD actions for WebAdminUser model. 
     */  
    class WebAdminUserRestController extends ActiveController  
    {  
        public $modelClass = 'app\models\Admin\WebAdminUser';

2.改web.php

    'urlManager' => [   
                        'enablePrettyUrl' => true,  
                        'showScriptName' => false,  
                        'enableStrictParsing' => true,  
                        'rules' => [   
                                '<controller:\w+>/<id:\d+>' => '<controller>/view',  
                                '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',  
                                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',  
                                '<ns:\w+>/<controller:[\w|-]+>/<action:\w+>' => '<ns>/<controller>/<action>',  
                                [   
                                        'class' => 'yii\rest\UrlRule',  
                                        'controller' =>  [  
                                            'admin/web-admin-user-rest'  
                                        ]   
                                ]  
                        ]   
                ]

调用 :

    $.get('http://localhost/admin/web-admin-user-rests',function(r){  
        console.log(r)  
    });

3.自定义action

    public function actionChecklogin(){  
        return true;  
    }