Yii2 RESTful 实践

安装 Yii

创建工作目录

mkdir yii2-rest
cd yii2-rest

创建 composer.json

{
    "require": {
        "yiisoft/yii2": "~2.0.0"
    },
    "repositories": [
        {
            "type": "composer",
            "url": "https://asset-packagist.org"
        }
    ]
}

然后运行 composer install 命令。

写一个 Hello World

创建 web/index.php

<?php

// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');

$config = require __DIR__ . '/../config.php';
(new yii\web\Application($config))->run();

创建 config.php

<?php

return [
    'id' => 'yii2-rest',
    // the basePath of the application will be the `yii2-rest` directory
    'basePath' => __DIR__,
    // this is where the application will find all controllers
    'controllerNamespace' => 'api\controllers',
    // set an alias to enable autoloading of classes from the 'api' namespace
    'aliases' => [
        '@api' => __DIR__,
    ],
];

创建 controllers/SiteController.php

<?php

namespace api\controllers;

use yii\web\Controller;

class SiteController extends Controller
{
    public function actionIndex()
    {
        return 'Hello World!';
    }
}

然后运行如下命令启动内置 web 服务器。

vendor/bin/yii serve --docroot=./web

在浏览器中打开 http://localhost:8080 应该就可以看到 “Hello World!”

创建一个 REST API

首先添加 MySQL 数据库配置。

'components' => [
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=127.0.0.1;dbname=rest_api',
        'username' => 'root',
        'password' => '123456',
        'charset' => 'utf8mb4',
    ],
]

然后使用 Yii Migrate 创建表。

vendor/bin/yii migrate/create --appconfig=config.php create_post_table --fields="title:string,body:text"
vendor/bin/yii migrate/up --appconfig=config.php

创建 models/Post.php

<?php

namespace api\models;

use yii\db\ActiveRecord;

class Post extends ActiveRecord
{ 
    public static function tableName()
    {
        return '{{post}}';
    }
}

创建 controller/PostController.php

<?php

namespace api\controllers;

use yii\rest\ActiveController;

class PostController extends ActiveController
{
    public $modelClass = 'api\models\Post';

    public function behaviors()
    {
        // remove rateLimiter which requires an authenticated user to work
        $behaviors = parent::behaviors();
        unset($behaviors['rateLimiter']);
        return $behaviors;
    }
}

启用 JSON 输入

'request' => [
    'parsers' => [
       'application/json' => 'yii\web\JsonParser',
    ]
],

配置URL规则

'urlManager' => [
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'rules' => [
        ['class' => 'yii\rest\UrlRule', 'controller' => 'post'],
    ],
],

现在我们就可以提供如下 REST API :

GET    /posts   - 列出所有帖子
GET    /posts/1 - 显示 ID 为 1 的帖子
POST   /posts   - 创建一个帖子
UPDATE /posts/1 - 更新 ID 为 1 的帖子
PATCH  /posts/1 - 更新 ID 为 1 的帖子
DELETE /posts/1 - 删除 ID 为 1 的帖子

参考:

https://www.yiiframework.com/doc/guide/2.0/zh-cn/tutorial-yii-as-micro-framework

https://github.com/tanghengzhi/yii2-rest

 484 total views,  4 views today

Leave a Reply

Your email address will not be published. Required fields are marked *