Implement a list of fetch cache components for RESTful applications in Yii 2 Starter Kit
1. Create the controller class of the cache component, \API\Controllers\CacheComponentController.php
* @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. Create the data layer of the resource class of the cache component (the corresponding model language package file), \common\models\redis\cachecomponent.php
Yii::t('model/redis/cache-component', 'ID'),
'name' => Yii::t('model/redis/cache-component', 'Name'),
];
}
}
3. Create the logical layer of the resource class of the cache component, \common\logics\redis\cachecomponent.php
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. In the interface application, create the resource class of the cache component, \API\Models\Redis\CacheComponent.php
5. In the V1 module of the interface application, create the resource class of the cache component, \api\modules\v1\models\redis\cachecomponent.php
6. In the V1 module of the interface application, create the controller class of the cache component, define the model class, \api\modules\v1\controllers\cacheComponentController.php
7. Create a method class that gets the list of cache components, \api\rests\cache_component\indexaction.php
* @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. Create a data serialization class that gets the list of cache components, \api\rests\cache_component\serializer.php
* @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. Add the routing configuration of the cache component list, edit \api\config\_urlmanager.php
[
'class' => 'yii\rest\UrlRule',
'controller' => ['v1/cache-component'],
'only' => ['index'],
],
10. GET request:http://www.cmcp-api.localhost/v1/cache-components?tenantid=default&api_gateway_user_id=1, the response is successful, as shown in Figure 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
}
}
}
