MixPHP 開發 API 接口簡單實例

注意:這個是 MixPHP V1 的範例

MixPHP 是一款基於 Swoole 的常駐內存型 PHP 高性能框架,框架的高性能特色很是適合開發 API 接口,並且很是接近傳統 MVC 框架,因此開發接口時很是簡單。php

下面作一個開發 API 接口的簡單實例:ios

articles 表,經過 id 獲取一篇文章。git

訪問該接口的 URL:github

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

數據庫表結構以下:sql

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

第二步

修改應用配置文件:json

  • 修改 Response 組件默認輸出格式爲 JSON 格式。
  • 修改 404/500 錯誤輸出格式爲 JSON 格式。

圖片2

框架默認的 404/500 響應是網頁,而 API 服務須要響應 JSON 數據,一般其餘傳統 MVC 框架須要修改不少地方纔可完成這個需求,MixPHP 自己就提供該種配置,只需修改一下配置便可。app

MixPHP 的默認 HTTP 應用中有兩個配置文件,分別爲:框架

  • http_permanent.php : 部署在 mix-httpd 的常駐同步模式時使用。
  • http_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\PDO;

class ArticlesModel
{

    const TABLE = 'articles';

    // 獲取一行數據經過id
    public function getRowById($id)
    {
        $sql = "SELECT * FROM `" . self::TABLE . "` WHERE id = :id";
        $row = PDO::createCommand($sql)->bindParams([
            'id' => $id,
        ])->queryOne();
        return $row;
    }

}

以上就是所有代碼的編寫。

第四步

使用 Postman 測試,以下:

圖片3

接口開發與測試完成,是否是很簡單呀。

MixPHP

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

相關文章
相關標籤/搜索