yii rest

环境搭建

phpstorm + phpstudy +xdebug

下载安装

REST

拷贝一个新的后台目录, 设置config/main.php中的id和控制器命名空间

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

设置url美化规则

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

main-local.php中设置json解析器

$config = [
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'fyw98YxydBk1tupwR89ghKaQvBnz0uRo',
            'parsers' => [
                'application/json'=>'yii\web\JsonParse',
            ]
        ],
    ],
];

修改nginx配置文件或者apache配置文件

控制器

继承 ActiveController

use yii\data\ActiveDataProvider;
use yii\rest\ActiveController;

class ArticleController extends ActiveController
{
    public $modelClass = 'common\models\Article';
}

字段获取

url附加fields参数

重写fields方法

在fields方法中通过匿名函数自定义字段的值

通过重写extrafields方法来忽略某些字段

分页

use yii\data\ActiveDataProvider;
use yii\rest\ActiveController;

class ArticleController extends ActiveController
{
    public $modelClass = 'common\models\Article';

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index']);
        return $actions;
    }

    function actionIndex(){
        $modelClass = $this->modelClass;
        return new ActiveDataProvider([
            'query'=>$modelClass::find()->asArray(),
            'pagination' => ['pageSize'=>5],
        ]);
    }
}

访问 http://apitpl.com/articles?page=2

搜索

在控制器中添加方法

    function actionSearch()
    {
        return $this->modelClass::find()->where(['like', 'title', $_POST['keyword']])->all();
    }

修改配置文件

        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                [
                    'class' => 'yii\rest\UrlRule',
                    'controller' => 'article',
                    'extraPatterns' => [
                        'POST search'=>'search',
                    ]
                ],
            ],
        ],

访问路径 http://apitpl.com/articles/search, post方式
body: keyword=''

自定义资源

继承 Controller, 不是 ActiveController
top10

use common\models\Article;
use yii\db\Query;
use yii\rest\ActiveController;
use yii\rest\Controller;

class TopController extends Controller
{

    public function actionIndex()
    {
        $all = Article::find()
            ->select([
                '序号' => 'article.id',
                '标题' => 'article.title',
                '状态' => 'article.status',
                '作者' => 'user.username'])
            ->leftjoin('user', 'user.id=article.created_by')
            ->orderBy('序号 desc')
            ->limit(5)
            ->asArray();



//        echo $all->createCommand()->getRawSql() . "\n";


//        $all = (new Query())
//            ->select(['article.id', 'article.title', 'user.username'])
//            ->from(['article', 'user'])
//            ->where('article.created_by=user.id')
//            ->orderBy('article.id desc')
//            ->limit(5);
//
//        echo $all->createCommand()->getRawSql() . "\n";


        return $all->all();
    }

}

如果函数不返回数据,而sql语句可以出数据,就调用asArray()方法

posted @ 2020-01-02 11:22  寒菱  阅读(198)  评论(0编辑  收藏  举报