The process of implementing RESTful web services based on Yii2 advanced application template under WindwoOS 10
1. Please refer to the previous blog:https://www.shuijingwanwq.com/en/2016/11/26/10288/
2. Prepare to implement RESTful web services based on shujujixi
3. Based on the GII generation model on the Frontend application, edit \environments\dev\frontend\config\main-local.php, as shown in Figure 1
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
'allowedIPs' => ['127.0.0.1', '::1'],
];
4. Execute .\init in Windows PowerShell to overwrite \frontend\config\main-local.php, and set the IP allowed by GII, as shown in Figure 2
5. Open the URL:http://www.kaiqiu_shujujiexi_api.dev/index.php?r=gii,可以访问GII, as shown in Figure 3
6. Edit \frontend\config\main.php to support URL beautification, as shown in Figure 4
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
7. Open the URL:http://www.kaiqiu_shujujiexi_api.dev/gii,如图5
8. Establish a corresponding model based on the database table KQ_Schedule, as shown in Figure 6
9. Click the Start button under the Model Generator to generate the model Schedule. The namespace is Common\Models, so that this model can be used by other applications in the later stage. At this time, there is no need to support internationalization, as shown in Figure 7
10. Click the Generate button to generate the model file\Common\Models\Schedule.php, as shown in Figure 8
11. Create a controller\shujujixi\controllers\schedulecontroller.php, as shown in Figure 9
12. Configure the url rules and modify the configuration of the urlmanager component, as shown in Figure 10
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'schedule',
],
],
],
13. In Postman, get: shujujixi.kaiqiu_shujujixi_api.dev/schedules, respond correctly, as shown in Figure 11
14. In order to implement its own business logic in the shujujixi application, it is recommended to create a new \shujujixi\mod els\schedule.php, which inherits to \common\models\schedule, as shown in Figure 12
15. Edit the controller\shujujixi\controllers\ScheduleController.php, and reassign the model to be shujujiexi\models\schedule, as shown in Figure 13
16. In Postman, get: shujujixi.kaiqiu_shujujixi_api.dev/schedules, correct response, as shown in Figure 11
17. Put in postman: shujujixi.kaiqiu_shujujixi_api.dev/schedules/1, correct response, as shown in Figure 14
18. Configure the ONLY and EXCEPT options to clarify which behavior support and which behavior is disabled. For example, if it only supports the GET list, you can modify the configuration of the URLManager component, as shown in Figure 15
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'schedule',
'only' => ['index'],
],
],
],
19. Put in postman: shujujixi.kaiqiu_shujujixi_api.dev/schedules/1, 404 responses, as shown in Figure 16
20. Based on the URL rules:get,head users=>user/index,, in postman head: shujujixi.kaiqiu_shujujixi_api.dev/schedules, empty response, you can ignore it, all other requests are 404, as shown in Figure 17
21. For the solution of the 404 response format is HTML, edit \shujujixi\config\main.php, and set the default response format to json, as shown in Figure 18
'response' => [
'format' => yii\web\Response::FORMAT_JSON,
],
22. Execute item 19 again, 404 response, its format is JSON, as shown in Figure 19
23. The realization of data serialization, including paging information in the response body to simplify the development of the client, edit \shujujixi\controllers\ScheduleController.php, as shown in Figure 20
public $serializer = [
'class' => 'yii\rest\Serializer',
'collectionEnvelope' => 'items',
];
24. In Postman, get: shujujixi.kaiqiu_shujujixi_api.dev/schedules, correct response, and include paging information in the response subject, as shown in Figure 21
25. RESTful APIs are usually stateless, so configure the user application component, edit \shujujixi\config\main.php, as shown in Figure 22
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => false,
'identityCookie' => ['name' => '_identity-shujujiexi', 'httpOnly' => true],
'enableSession' => false,
'loginUrl' => null,
],
26. The implementation of versioning, create a new directory\shujujixi\modules, its structure is shown in Figure 23
27, \shujujixi\modules\v1\module.php, its content, as shown in Figure 24
28, \shujujixi\modules\v1\controllers\schedulecontroller.php, its contents, as shown in Figure 25
29, \shujujixi\modules\v1\models\schedule.php, its content, as shown in Figure 26
30. Configure the url rules and modify the configuration of the urlmanager component, as shown in Figure 27
31. Configure the module rules, as shown in Figure 28
'modules' => [
'v1' => [
'basePath' => '@app/modules/v1',
'class' => 'shujujiexi\modules\v1\Module'
],
],
31. In Postman, get: shujujixi.kaiqiu_shujujixi_api.dev/schedules, 404 responses, in line with expectations, as shown in Figure 29
32. In Postman, get: shujujixi.kaiqiu_shujujixi_api.dev/v1/schedules, correct response, as shown in Figure 30
33. Response to the structural adjustment of the data, the default is code, message, data fields
34. Copy\vendor\yiisoft\yii2\rest\serializer.php to \shujujixi\rests\seria Lizer.php, its content, inherited to \yii\rest\serializer, and only keeps the SerializedDataProvider(), as shown in Figure 31
* @since 2.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;
} else {
$result = [
$this->collectionEnvelope => $models,
];
if ($pagination !== false) {
return ['code' => '00000', 'message' => 'success', 'data' => array_merge($result, $this->serializePagination($pagination))];
// return array_merge($result, $this->serializePagination($pagination));
} else {
return ['code' => '00000', 'message' => 'success', 'data' => $result];
// return $result;
}
}
}
}
35. Edit the controller\shujujixi\controllers\schedulecontroller.php, as shown in Figure 32
36. In Postman, get: shujujixi.kaiqiu_shujujixi_api.dev/v1/schedules, correct response, as shown in Figure 33
37. How to freely define the implementation process of the response of this request, analyze\vendor\yiisoft\yii2\rest\active Controller.php can be found that the default implementation of the index operation is yii\rest\indexAction, as shown in Figure 34
38. Copy \vendor\yiisoft\yii2\rest\indexaction.php to \shujujixi\rests\schedule\indexaction.php, as shown in Figure 35
39. Edit the controller\shujujixi\controllers\schedulecontroller.php, as shown in Figure 36
public function actions()
{
$actions = parent::actions();
$actions['index']['class'] = 'shujujiexi\rests\schedule\IndexAction';
return $actions;
}
40, edit\shujujixi\rests\schedule\indexaction.php, as shown in Figure 37
* @since 2.0
*/
class IndexAction extends rest\IndexAction
{
/**
* @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]].
*/
/**
* 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 $modelClass \yii\db\BaseActiveRecord */
$modelClass = $this->modelClass;
return new ActiveDataProvider([
'query' => $modelClass::find()->where(['status' => 1]),
]);
}
}
41. In postman, get: shujujixi.kaiqiu_shujujixi_api.dev/v1/schedules, correct response, and only return data with status 1, as shown in Figure 38
Remarks:
1. The model file generated by GII is stored in the Common directory;
2. V1, the method in the controller and model is recommended to be implemented in \shujujixi\controllers, \shujujixi\models;
3. If you need to have different functional implementations, the methods in the controller and model are recommended to be in \shujujixi\modules \v1\Controllers, \shujujixi\modules\v1\Models is covered implementation;
4. shujujixi\rests, its directory structure is similar to shujujixi\views, and each controller has its corresponding directory;
5. In each major version (in the corresponding module), use the Accept HTTP request header to determine the small version number to write the condition code to respond to the corresponding secondary version;
// pass parameters
accept: application/json; version=1.0.0






































