在 Yii 2 Starter Kit 中实现 RESTful 应用的获取缓存组件列表

1、创建缓存组件的控制器类,/api/controllers/CacheComponentController.php

<?php
namespace api/controllers;

use yii/rest/ActiveController;

/**
 * Class CacheComponentController
 * @package api/controllers
 *
 * @author Qiang Wang <shuijingwanwq@163.com>
 * @since 1.0
 */
class CacheComponentController extends ActiveController
{
    public $serializer = [
        'class' => 'api/rests/cache_component/Serializer',
        'collectionEnvelope' => 'items',
    ];

    /**
     * @inheritdoc
     */
    public function actions()
    {
        $actions = parent::actions();
        // 禁用"view"、"create"、"update"、"delete"、"options"动作
        unset($actions['view'], $actions['create'], $actions['update'], $actions['delete'], $actions['options']);
        $actions['index']['class'] = 'api/rests/cache_component/IndexAction';
        return $actions;
    }
}

2、创建缓存组件的资源类的数据层(相应的模型语言包文件),/common/models/redis/CacheComponent.php

<?php

namespace common/models/redis;

use Yii;
use common/components/redis/ActiveRecord;

/**
 * This is the model class for table "{{%cache_component}}".
 *
 * @property int $id
 * @property string $name 组件ID
 */
class CacheComponent extends ActiveRecord
{
    /**
     * @return array the list of attributes for this record
     */
    public function attributes()
    {
        return ['id', 'name'];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'name'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('model/redis/cache-component', 'ID'),
            'name' => Yii::t('model/redis/cache-component', 'Name'),
        ];
    }
}

3、创建缓存组件的资源类的逻辑层,/common/logics/redis/CacheComponent.php

<?php

namespace common/logics/redis;

use Yii;

class CacheComponent extends /common/models/redis/CacheComponent
{
    /**
     * Returns array of caches in the system, keys are cache components names, values are class names.
     * @param array $cachesNames caches to be found
     * @return array
     */
    function getCacheComponents(array $cachesNames = [])
    {
        $caches = [];
        $components = Yii::$app->getComponents();
        $findAll = ($cachesNames == []);

        foreach ($components as $name => $component) {
            if (!$findAll && !in_array($name, $cachesNames)) {
                continue;
            }

            if ($component instanceof Cache) {
                $caches[$name] = ['name'=>$name, 'class'=>get_class($component)];
            } elseif (is_array($component) && isset($component['class']) && $this->isCacheClass($component['class'])) {
                $caches[$name] = ['name'=>$name, 'class'=>$component['class']];
            } elseif (is_string($component) && $this->isCacheClass($component)) {
                $caches[$name] = ['name'=>$name, 'class'=>$component];
            }
        }

        return $caches;
    }

    /**
     * Checks if given class is a Cache class.
     * @param string $className class name.
     * @return boolean
     */
    private function isCacheClass($className)
    {
        return is_subclass_of($className, Cache::className());
    }


}

4、在接口应用中,创建缓存组件的资源类,/api/models/redis/CacheComponent.php

<?php

namespace api/models/redis;

class CacheComponent extends /common/logics/redis/CacheComponent
{

}

5、在接口应用的v1模块中,创建缓存组件的资源类,/api/modules/v1/models/redis/CacheComponent.php

<?php

namespace api/modules/v1/models/redis;

class CacheComponent extends /api/models/redis/CacheComponent
{

}

6、在接口应用的v1模块中,创建缓存组件的控制器类,定义模型类,/api/modules/v1/controllers/CacheComponentController.php

<?php

namespace api/modules/v1/controllers;

/**
 * CacheComponent controller for the `v1` module
 */
class CacheComponentController extends /api/controllers/CacheComponentController
{
    public $modelClass = 'api/modules/v1/models/redis/CacheComponent';
}

7、创建获取缓存组件列表的方法类,/api/rests/cache_component/IndexAction.php

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace api/rests/cache_component;

use Yii;
use yii/data/ArrayDataProvider;

/**
 * IndexAction implements the API endpoint for listing multiple models.
 *
 * For more details and usage information on IndexAction, see the [guide article on rest controllers](guide:rest-controllers).
 *
 * @author Qiang Wang <shuijingwanwq@163.com>
 * @since 1.0
 */
class IndexAction extends /yii/rest/IndexAction
{
    /**
     * Prepares the data provider that should return the requested collection of the models.
     * @return ActiveDataProvider
     */
    protected function prepareDataProvider()
    {
        $requestParams = Yii::$app->getRequest()->getBodyParams();
        if (empty($requestParams)) {
            $requestParams = Yii::$app->getRequest()->getQueryParams();
        }

        $filter = null;
        if ($this->dataFilter !== null) {
            $this->dataFilter = Yii::createObject($this->dataFilter);
            if ($this->dataFilter->load($requestParams)) {
                $filter = $this->dataFilter->build();
                if ($filter === false) {
                    return $this->dataFilter;
                }
            }
        }

        if ($this->prepareDataProvider !== null) {
            return call_user_func($this->prepareDataProvider, $this, $filter);
        }

        /* @var $modelClass /yii/db/BaseActiveRecord */
        $modelClass = $this->modelClass;
        $model = new $modelClass();

        $allModels = $model->getCacheComponents();

        return Yii::createObject([
            'class' => ArrayDataProvider::className(),
            'allModels' => $allModels,
            'pagination' => [
                'params' => $requestParams,
            ],
            'sort' => [
                'params' => $requestParams,
            ],
        ]);
    }
}

8、创建获取缓存组件列表的数据序列化类,/api/rests/cache_component/Serializer.php

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace api/rests/cache_component;

use Yii;
use yii/data/DataProviderInterface;

/**
 * Serializer converts resource objects and collections into array representation.
 *
 * Serializer is mainly used by REST controllers to convert different objects into array representation
 * so that they can be further turned into different formats, such as JSON, XML, by response formatters.
 *
 * The default implementation handles resources as [[Model]] objects and collections as objects
 * implementing [[DataProviderInterface]]. You may override [[serialize()]] to handle more types.
 *
 * @author Qiang Wang <shuijingwanwq@163.com>
 * @since 1.0
 */
class Serializer extends /yii/rest/Serializer
{
    /**
     * Serializes a data provider.
     * @param DataProviderInterface $dataProvider
     * @return array the array representation of the data provider.
     */
    protected function serializeDataProvider($dataProvider)
    {
        if ($this->preserveKeys) {
            $models = $dataProvider->getModels();
        } else {
            $models = array_values($dataProvider->getModels());
        }
        $models = $this->serializeModels($models);

        if (($pagination = $dataProvider->getPagination()) !== false) {
            $this->addPaginationHeaders($pagination);
        }

        if ($this->request->getIsHead()) {
            return null;
        } elseif ($this->collectionEnvelope === null) {
            return $models;
        }

        $result = [
            $this->collectionEnvelope => $models,
        ];

        if (empty($result['items'])) {
            return ['code' => 20013, 'message' => Yii::t('error', '20013')];
        }

        if ($pagination !== false) {
            return ['code' => 10000, 'message' => Yii::t('app', '10007'), 'data' => array_merge($result, $this->serializePagination($pagination))];
        }

        return ['code' => 10000, 'message' => Yii::t('app', '10007'), 'data' => $result];
    }
}

9、新增获取缓存组件列表的路由配置,编辑 /api/config/_urlManager.php

        [
            'class' => 'yii/rest/UrlRule',
            'controller' => ['v1/cache-component'],
            'only' => ['index'],
        ],

10、GET 请求:http://www.cmcp-api.localhost/v1/cache-components?tenantid=default&api_gateway_user_id=1 ,响应成功,如图1

{
    "code": 10000,
    "message": "获取缓存组件列表成功",
    "data": {
        "items": [
            {
                "name": "cache",
                "class": "yii//caching//DummyCache"
            },
            {
                "name": "redisCache",
                "class": "yii//redis//Cache"
            },
            {
                "name": "frontendCache",
                "class": "yii//caching//DummyCache"
            }
        ],
        "_links": {
            "self": {
                "href": "http://www.cmcp-api.localhost/v1/cache-components?tenantid=default&api_gateway_user_id=1&page=1"
            }
        },
        "_meta": {
            "totalCount": 3,
            "pageCount": 1,
            "currentPage": 1,
            "perPage": 20
        }
    }
}
GET 请求:http://www.cmcp-api.localhost/v1/cache-components?tenantid=default&api_gateway_user_id=1 ,响应成功

图1

原创文章,作者:3628473679,如若转载,请注明出处:https://blog.ytso.com/180974.html

(0)
上一篇 2021年10月31日
下一篇 2021年10月31日

相关推荐

发表回复

登录后才能评论