matthew-p/yii2-extended-api

扩展了Yii2 API标准类的功能

2.0.0 2020-02-19 12:27 UTC

This package is auto-updated.

Last update: 2023-08-19 20:53:50 UTC


README

该包扩展了Yii2 API标准类的功能

Latest Stable Version node (scoped with tag) Coverage Status Scrutinizer Code Intelligence Software License composer.lock

安装

安装此扩展的首选方式是通过 composer

运行以下命令之一:

php composer.phar require --prefer-dist matthew-p/yii2-extended-api "*"

或添加以下内容到您的 composer.json 文件中的 require 部分:

"matthew-p/yii2-extended-api": "@dev"

to the require section of your composer.json file.

使用

扩展安装后,只需在代码中使用即可

例如,为 ExampleProduct 模型使用 REST 控制器

use MP\ExtendedApi\EActiveController;

class ProductsController extends EActiveController
{
    /**
     * @var string
     */
    public $modelClass = ExampleProduct::class;

    /**
     * @var string
     */
    public $searchClass = ExampleProductSearch::class;

    /**
     * @var bool
     */
    public $errorFilter = true;
    
    /**
     * @var array
     */
    public $externalActions = [
        'delete-all' => true,
    ];

    /**
     * @inheritdoc
     */
    public function behaviors(): array
    {
        return array_merge(parent::behaviors(), [
            'authenticator' => [
                'class' => HttpBearerAuth::class,
            ],
            'access'        => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => [User::ROLE_API],
                    ],
                ],
            ],
        ]);
    }

    /**
     * @inheritdoc
     * @throws NotFoundHttpException
     */
    public function filterError()
    {
        throw new NotFoundHttpException(Yii::t('app', 'Product not found'), self::FILTER_ERROR_CODE);
    }
}

为 ExampleProduct 使用 REST 搜索模型

use MP\ExtendedApi\ModelSearchInterface;

class ExampleProductSearch extends ExampleProduct implements ModelSearchInterface
{
    /**
     * @inheritdoc
     */
    public function rules(): array
    {
        // model rules ...
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search(array $params = []): ActiveDataProvider
    {
        $dataProvider = $this->getDataProvider();

        $query = $dataProvider->query;

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions

        return $dataProvider;
    }

    /**
     * @inheritdoc
     */
    public function getDataProvider(): ActiveDataProvider
    {
        return new ActiveDataProvider([
            'query'      => self::find(),
            'pagination' => [
                'defaultPageSize' => 20,
                'pageSizeLimit'   => [
                    0, 20, 50, 100,
                ],
            ],
        ]);
    }
}

特性

  • 删除所有模型操作(支持筛选,添加头信息)
  • 更新所有模型操作(支持筛选,添加头信息)
  • 通过自定义数据提供者进行筛选
  • 如果筛选结果为空,则自定义错误
  • 视图操作触发
// In controller
$this->action->on(EViewAction::EVENT_RUN_VIEW_ACTION, function (Event $event) use ($action) {
    // you code...
});
  • 编辑筛选参数
//  public function beforeAction($action) in controller
if ($action instanceof EIndexAction) {
    $filterParams = $action->getFilterParams();

    $filterParams['active'] = ExampleProduct::STATUS_ACTIVE;

    $action->setFilterParams($filterParams);
}
  • 在准备数据提供者之后触发
  • delete 动作获取已删除的模型
// public function afterAction($action, $result)
if ($action instanceof EDeleteAction) {
    $model = $action->getModel();
}
  • indexdelete-all 动作自定义查询条件
use MP\ExtendedApi\EActiveController;

class ProductsController extends EActiveController
{
    public $actionsParams = [
       'index' => [
           'addQuery' => [self::class, 'customCondition'],
       ],
    ];
    
    public static function customCondition($query)
    {
        ...
    }
...
  • indexdelete-all 动作按用户筛选
use MP\ExtendedApi\EActiveController;

class ProductsController extends EActiveController
{
    public $actionsParams = [
       'index' => [
           'filterUser' => 'user_id', // table column name
       ],
    ];
   
...

就这么多。试试吧。