yii2 RESTful API(一)

今天我们简单搭建一个RESTful API服务,yii2 是个好东西,做接口更方便一些。
在实际的开发中,我们还是要进行一些优化。这一节我们记录一下怎么搭建。个人水平有限,仅做参考。

一 、首先复制一个目录进行修改,并在 bootstrap.php 文件中做一下配置,

Yii::setAlias('@app', dirname(dirname(__DIR__)) . '/app');

在这里插入图片描述

二 、目录配置好后,检测一下命名空间。之后看一下app 目录下的配置文件 main.php,一写注释我都下面的文件里了。

/yii2advanced/app/config/main.php
<?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

return [
    'id' => 'app-api',//修改
    'basePath' => dirname(__DIR__),
    'controllerNamespace' => 'api\controllers',//修改
    'bootstrap' => ['log'],
    'modules' => [],
    'components' => [

        'cache' => [
            'class' => 'yii\caching\ApcCache',
        ],
        'request' => [
            'csrfParam' => '_csrf-backend',
        ],
        //把Cookie 和 session api 开发是不需要的。 
        'user' => [
            'identityClass' => 'common\models\Adminuser',
            'enableAutoLogin' => true,
            'enableSession' => false,
            //'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
        ],
//         'session' => [
//             // this is the name of the session cookie used for login on the backend
//             'name' => 'advanced-backend',
//         ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],

        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
       
                
            ],
        ],
        
    ],
    'params' => $params,
];

找到/yii2advanced/app/config/main-local.php 文件
  //返回json
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ]
            
$config = [
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'jWDInnwhXOmKRPMQAVI_-sDHsZncjlbR',
            //返回json
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ]
        ],
    ],
];

if (!YII_ENV_TEST) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
    ];

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
    ];
}

return $config;

三、我们可以用gii 生成一个model ,之后我们要创建一个控制器。如下:

<?php
namespace api\controllers;

use yii\rest\ActiveController;
use yii\data\ActiveDataProvider;
use common\models\Article;
use yii\helpers\ArrayHelper;
use yii\filters\auth\QueryParamAuth;
use common\models\Adminuser;
use yii\filters\auth\HttpBasicAuth;

class ArticleController extends ActiveController
{
    //api 统一这样写,把他去掉换成别的写法有可能会报错
    public $modelClass = 'common\models\Article';
 

   //API 已经内置了基本功能,满足不了你的需求,你可以unset自己写。
    public  function actions()
    {
        $actions = parent::actions();
        unset($actions['index']);
        return $actions;
    }
   //这是重写的index方法
    public function actionIndex()
    {
        $modelClass = $this->modelClass;
        return new ActiveDataProvider(
                [
                    'query'=>$modelClass::find()->asArray(),
                    'pagination'=>['pageSize'=>5],
                ]
            );
    }
     //这是自定义的搜索方法
    public function actionSearch() {
        return Article::find()->where(['like','title',$_POST['keyword']])->all();
    }
    
 
}

四、我们把控制器的基本方法写好了。下面我们就要该配置路由了。还是在main.php文件中配置,

 'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                ['class' => 'yii\rest\UrlRule', 
                    'controller' => 'article',
                    'ruleConfig'=>[
                        'class'=>'yii\web\UrlRule',
                        'defaults'=>[
                            'expand'=>'createdBy',
                        ]
                    ],
                    'extraPatterns'=>[
                        'POST search' => 'search'
                    ],
                ],
                
                ['class'=>'yii\rest\UrlRule',
                    'controller'=>'top10',
                    'except'=>['delete','create','update','view'],
                    'pluralize'=>false,
                ],
                
                [
                    'class'=>'yii\rest\UrlRule',
                    'controller'=>'adminuser',//控制器 注意要小写
                    'except'=>['delete','create','update','view'], //除了这些方法,其他都可以
                    'pluralize'=>false,//不用加后缀s
                    'extraPatterns' => [
                        'POST login' => 'login', //自定义的方法
                    ]
                    
                ],
                
                
            ],
        ],
        
    ],

五、路由配置好了,正常来说我们是可以访问了。接口测试工具我是用Postman
在这里插入图片描述
今天聊到这,下次继续。如果想深入的了解yii,参考一下的链接:

https://www.yiichina.com/

http://www.digpage.com/index.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值