MixPHP 开发 API 接口简单实例

作者: 撸代码的乡下人 | 来源:发表于2018-03-08 17:53 被阅读120次

    MixPHP 是一款基于 Swoole 的常驻内存型 PHP 高性能框架,框架的高性能特点非常适合开发 API 接口,而且 MixPHP 非常接近传统 MVC 框架,所以开发接口时非常简单。

    下面做一个开发 API 接口的简单实例:

    articles 表,通过 id 获取一篇文章。

    访问该接口的 URL:

    http://www.e.com/articles/details?id=1
    

    数据库表结构如下:

    CREATE TABLE `articles` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `title` varchar(255) NOT NULL,
      `content` varchar(255) NOT NULL,
      `dateline` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    

    第一步

    修改数据库配置文件,MixPHP 的应用配置文件中,关于数据库的信息都引用了 common/config/database.php 文件。

    图片1

    第二步

    修改应用配置文件:

    • 修改 Response 组件默认输出格式为 JSON 格式。
    • 修改 404/500 错误输出格式为 JSON 格式。
    图片2

    框架默认的 404/500 响应是网页,而 API 服务需要响应 JSON 数据,通常其他传统 MVC 框架需要修改很多地方才可完成这个需求,MixPHP 本身就提供该种配置,只需修改一下配置即可。

    MixPHP 的默认 Web 应用中有两个配置文件,分别为:

    • main.php : 部署在 mix-httpd 时使用。
    • main_compatible.php :部署在 Apache/PHP-FPM 时使用。

    开发 API 时我们推荐在 Apache/PHP-FPM 下开发,上线再部署至 mix-httpd 即可,反正是无缝切换的。

    现在我们修改 response 键名下的 defaultFormat 键为 mix\http\Error::FORMAT_JSON,如下:

    // 响应
    'response' => [
        // 类路径
        'class'         => 'mix\http\compatible\Response',
        // 默认输出格式
        'defaultFormat' => mix\http\Response::FORMAT_JSON,
        // json
        'json'          => [
            // 类路径
            'class' => 'mix\http\Json',
        ],
        // jsonp
        'jsonp'         => [
            // 类路径
            'class' => 'mix\http\Jsonp',
            // callback键名
            'name'  => 'callback',
        ],
        // xml
        'xml'           => [
            // 类路径
            'class' => 'mix\http\Xml',
        ],
    ],
    

    然后修改 main_compatible.php 文件中 error 键名下的 format 键为 mix\http\Error::FORMAT_JSON,如下:

    // 错误
    'error'    => [
        // 类路径
        'class'  => 'mix\http\Error',
        // 输出格式
        'format' => mix\http\Error::FORMAT_JSON,
    ],
    

    第三步

    创建控制器:

    apps/index/controllers/ArticlesController.php
    
    <?php
    
    namespace apps\index\controllers;
    
    use mix\facades\Request;
    use mix\http\Controller;
    use apps\index\messages\ErrorCode;
    use apps\index\models\ArticlesForm;
    
    class ArticlesController extends Controller
    {
    
        public function actionDetails()
        {
            // 使用模型
            $model             = new ArticlesForm();
            $model->attributes = Request::get();
            $model->setScenario('actionDetails');
            if (!$model->validate()) {
                return ['code' => ErrorCode::INVALID_PARAM];
            }
            // 获取数据
            $data = $model->getDetails();
            if (!$data) {
                return ['code' => ErrorCode::ERROR_ID_UNFOUND];
            }
            // 响应
            return ['code' => ErrorCode::SUCCESS, 'data' => $data];
        }
    
    }
    

    创建错误码类:

    apps/index/messages/ErrorCode.php
    
    <?php
    
    namespace apps\index\messages;
    
    class ErrorCode
    {
    
        const SUCCESS = 0;
        const INVALID_PARAM = 100001;
        const ERROR_ID_UNFOUND = 200001;
    
    }
    

    创建表单验证模型:

    apps/index/models/ArticlesForm.php
    
    <?php
    
    namespace apps\index\models;
    
    use mix\validators\Validator;
    use apps\common\models\ArticlesModel;
    
    class ArticlesForm extends Validator
    {
    
        public $id;
    
        // 规则
        public function rules()
        {
            return [
                'id' => ['integer', 'unsigned' => true, 'maxLength' => 10],
            ];
        }
    
        // 场景
        public function scenarios()
        {
            return [
                'actionDetails' => ['required' => ['id']],
            ];
        }
    
        // 获取详情
        public function getDetails()
        {
            return (new ArticlesModel())->getRowById($this->id);
        }
    
    }
    

    创建数据表模型:

    apps/common/models/ArticlesModel.php
    
    <?php
    
    namespace apps\common\models;
    
    use mix\facades\RDB;
    
    class ArticlesModel
    {
    
        const TABLE = 'articles';
    
        // 获取一行数据通过id
        public function getRowById($id)
        {
            $sql = "SELECT * FROM `" . self::TABLE . "` WHERE id = :id";
            $row = RDB::createCommand($sql)->bindParams([
                'id' => $id,
            ])->queryOne();
            return $row;
        }
    
    }
    

    以上就是全部代码的编写。

    第四步

    使用 Postman 测试,如下:

    图片3

    接口开发与测试完成,是不是很简单呀。

    MixPHP

    GitHub: https://github.com/mixstart/mixphp
    官网:http://www.mixphp.cn/

    相关文章

      网友评论

        本文标题:MixPHP 开发 API 接口简单实例

        本文链接:https://www.haomeiwen.com/subject/jchyfftx.html