Yii2 REST查询

Ked*_*nor 19 api rest yii2

HY.我有一个ProductController,它扩展了yii\rest\ActiveController.问题是如何通过HTTP GET请求进行查询.

喜欢:http://api.test.loc/v1/products/search?name = iphone

返回对象将包含名为iphone的所有产品.

Sal*_*ani 37

更新:2016年4月29日

这是我在上一次更新中介绍的方法之一.它总是涉及由gii生成的Search类.我喜欢用它在一个地方定义和维护所有与搜索相关的逻辑,比如使用自定义场景,处理验证或在过滤过程中涉及相关模型(如本例所示).所以我要回到我的第一个答案:

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

public function prepareDataProvider() 
{
    $searchModel = new \app\models\ProductSearch();    
    return $searchModel->search(\Yii::$app->request->queryParams);
}
Run Code Online (Sandbox Code Playgroud)

然后确保您的搜索类正在使用load($params,'')而不是load($params)或者将其添加到模型类:

class Product extends \yii\db\ActiveRecord
{
    public function formName()
    {
        return '';
    }
Run Code Online (Sandbox Code Playgroud)

这应该足以让您的请求看起来像:

/产品?名称= iphone&状态=可用&排序=名称,购正价


更新:2015年9月23日

这是相同的方法,但通过实施一个完整和清洁的解决方案:

namespace app\api\modules\v1\controllers;

use yii\rest\ActiveController;
use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;

class ProductController extends ActiveController
{
    public $modelClass = 'app\models\Product';
    // Some reserved attributes like maybe 'q' for searching all fields at once 
    // or 'sort' which is already supported by Yii RESTful API
    public $reservedParams = ['sort','q'];

    public function actions() {
        $actions = parent::actions();
        // 'prepareDataProvider' is the only function that need to be overridden here
        $actions['index']['prepareDataProvider'] = [$this, 'indexDataProvider'];
        return $actions;
    }

    public function indexDataProvider() {
        $params = \Yii::$app->request->queryParams;

        $model = new $this->modelClass;
        // I'm using yii\base\Model::getAttributes() here
        // In a real app I'd rather properly assign 
        // $model->scenario then use $model->safeAttributes() instead
        $modelAttr = $model->attributes;

        // this will hold filtering attrs pairs ( 'name' => 'value' )
        $search = [];

        if (!empty($params)) {
            foreach ($params as $key => $value) {
                // In case if you don't want to allow wired requests
                // holding 'objects', 'arrays' or 'resources'
                if(!is_scalar($key) or !is_scalar($value)) {
                    throw new BadRequestHttpException('Bad Request');
                }
                // if the attr name is not a reserved Keyword like 'q' or 'sort' and 
                // is matching one of models attributes then we need it to filter results
                if (!in_array(strtolower($key), $this->reservedParams) 
                    && ArrayHelper::keyExists($key, $modelAttr, false)) {
                    $search[$key] = $value;
                }
            }
        }

        // you may implement and return your 'ActiveDataProvider' instance here.
        // in my case I prefer using the built in Search Class generated by Gii which is already 
        // performing validation and using 'like' whenever the attr is expecting a 'string' value.
        $searchByAttr['ProductSearch'] = $search;
        $searchModel = new \app\models\ProductSearch();    
        return $searchModel->search($searchByAttr);     
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您的GET请求将如下所示:

/产品?名称= iphone

甚至喜欢:

/产品?名称= iphone&状态=可用&排序=名称,购正价

  • 注意:

    如果/products?name=iphone您正在寻找特定的操作来处理搜索或过滤请求,而不是:

    /产品/搜索?NAME = iphone

    然后,在上面的代码中,您需要删除 actions函数及其所有内容:

    public function actions() { ... }

    重命名:indexDataProvider()actionSearch()

    最后添加 'extraPatterns' => ['GET search' => 'search']到你的 yii\web\UrlManager ::规则,如@ KedvesHunor的回答中所述.


原答案:2015年5月31日

有一个简短的方法可以做到这一点,如果使用Gii为您的模型生成CRUD,您定义了一个搜索模型类,然后您可以使用它来过滤结果,您所要做的就是覆盖强制它的prepareDataProvider功能indexAction返回模型搜索类函数返回的ActiveDataProvider实例,而不是创建自定义新实例.search

要恢复你的模型是Product.php并且你生成了一个ProductSearch.php作为它的搜索类,那么在你的Controller中你只需要添加:

public function actions() {

    $actions = parent::actions();
    $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];

    return $actions;
}

public function prepareDataProvider() {

    $searchModel = new \app\models\ProductSearch();    
    return $searchModel->search(\Yii::$app->request->queryParams);
}
Run Code Online (Sandbox Code Playgroud)

然后要过滤结果,您的网址可能如下所示:

api.test.loc/v1/products?ProductSearch[name]=iphone
Run Code Online (Sandbox Code Playgroud)

或者甚至喜欢这样:

api.test.loc/v1/products?ProductSearch[available]=1&ProductSearch[name]=iphone
Run Code Online (Sandbox Code Playgroud)


Ked*_*nor 25

好吧我想通了,只需将它放在你的控制器中并修改配置中的URL路由器.

public function actionSearch()
{
    if (!empty($_GET)) {
        $model = new $this->modelClass;
        foreach ($_GET as $key => $value) {
            if (!$model->hasAttribute($key)) {
                throw new \yii\web\HttpException(404, 'Invalid attribute:' . $key);
            }
        }
        try {
            $provider = new ActiveDataProvider([
                'query' => $model->find()->where($_GET),
                'pagination' => false
            ]);
        } catch (Exception $ex) {
            throw new \yii\web\HttpException(500, 'Internal server error');
        }

        if ($provider->getCount() <= 0) {
            throw new \yii\web\HttpException(404, 'No entries found with this query string');
        } else {
            return $provider;
        }
    } else {
        throw new \yii\web\HttpException(400, 'There are no query string');
    }
}
Run Code Online (Sandbox Code Playgroud)

和URL规则(编辑)

'urlManager' => [
        'enablePrettyUrl' => true,
        'enableStrictParsing' => true,
        'showScriptName' => false,
        'rules' => [
            ['class' => 'yii\rest\UrlRule', 'controller' => ['v1/product'], 'extraPatterns' => ['GET search' => 'search']],
        ],
    ],
Run Code Online (Sandbox Code Playgroud)


小智 8

我不建议直接使用Superglobals $ _GET.相反,您可以使用Yii :: $ app-> request-> get().

以下是如何创建通用搜索操作并在控制器中使用它的示例.

在控制器端

public function actions() {

$actions = [
    'search' => [
        'class'       => 'app\[YOUR NAMESPACE]\SearchAction',
        'modelClass'  => $this->modelClass,
        'checkAccess' => [$this, 'checkAccess'],
        'params'      => \Yii::$app->request->get()
    ],
];

return array_merge(parent::actions(), $actions);
}

public function verbs() {

    $verbs = [
        'search'   => ['GET']
    ];
    return array_merge(parent::verbs(), $verbs);
}
Run Code Online (Sandbox Code Playgroud)

自定义搜索操作

<?php

namespace app\[YOUR NAMESPACE];

use Yii;
use yii\data\ActiveDataProvider;
use yii\rest\Action;


class SearchAction extends Action {

    /**
     * @var callable a PHP callable that will be called to prepare a data provider that
     * should return a collection of the models. If not set, [[prepareDataProvider()]] will be used instead.
     * The signature of the callable should be:
     *
     * ```php
     * function ($action) {
     *     // $action is the action object currently running
     * }
     * ```
     *
     * The callable should return an instance of [[ActiveDataProvider]].
     */
    public $prepareDataProvider;
    public $params;

    /**
     * @return ActiveDataProvider
     */
    public function run() {
        if ($this->checkAccess) {
            call_user_func($this->checkAccess, $this->id);
        }

        return $this->prepareDataProvider();
    }

    /**
     * Prepares the data provider that should return the requested collection of the models.
     * @return ActiveDataProvider
     */
    protected function prepareDataProvider() {
        if ($this->prepareDataProvider !== null) {
            return call_user_func($this->prepareDataProvider, $this);
        }

        /**
         * @var \yii\db\BaseActiveRecord $modelClass
         */
        $modelClass = $this->modelClass;

        $model = new $this->modelClass([
        ]);

        $safeAttributes = $model->safeAttributes();
        $params = array();

        foreach($this->params as $key => $value){
            if(in_array($key, $safeAttributes)){
               $params[$key] = $value;                
            }
        }

        $query = $modelClass::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (empty($params)) {
            return $dataProvider;
        }


        foreach ($params as $param => $value) {
            $query->andFilterWhere([
                $param => $value,
            ]);
        }

        return $dataProvider;
    }

}
Run Code Online (Sandbox Code Playgroud)