How to use MixPHP to develop API interfaces

不言
Release: 2023-04-03 06:14:01
Original
3686 people have browsed it

This article mainly introduces how to use MixPHP to develop API interfaces. It has certain reference value. Now I share it with you. Friends in need can refer to it

MixPHP is a common software based on Swoole. A memory-based PHP high-performance framework, the high-performance features of the framework are very suitable for developing API interfaces, and MixPHP is very close to the traditional MVC framework, so it is very simple to develop interfaces.

The following is a simple example of developing an API interface:

Get an article from the articles table through id.

URL to access this interface:

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

The database table structure is as follows:

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;
Copy after login

Step 1

Modify the database configuration file, MixPHP In the application configuration file, information about the database refers to the common/config/database.php file.

How to use MixPHP to develop API interfaces

Step 2

Modify the application configuration file:

  • Modify the default output format of the Response component to JSON format .

  • Modify the 404/500 error output format to JSON format.

How to use MixPHP to develop API interfaces

The default 404/500 response of the framework is a web page, and the API service needs to respond to JSON data. Usually other traditional MVC frameworks need to modify many places. To meet this requirement, MixPHP itself provides this configuration, and you only need to modify the configuration.

MixPHP's default web application has two configuration files, namely:

  • main.php: used when deployed in mix-httpd.

  • main_compatible.php: Used when deployed in Apache/PHP-FPM.

When developing API, we recommend developing it under Apache/PHP-FPM, and then deploying it to mix-httpd after going online. Anyway, it will be seamless switching.

Now we modify the defaultFormat key under the response key name to mix\http\Error::FORMAT_JSON, as follows:

// 响应
'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',
    ],
],
Copy after login

Then modify the format key under the error key name in the main_compatible.php file to mix\http\Error::FORMAT_JSON, as follows:

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

Step 3

Create controller:

apps/index/controllers/ArticlesController.php
Copy after login
<?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(&#39;actionDetails&#39;);
        if (!$model->validate()) {
            return [&#39;code&#39; => ErrorCode::INVALID_PARAM];
        }
        // 获取数据
        $data = $model->getDetails();
        if (!$data) {
            return [&#39;code&#39; => ErrorCode::ERROR_ID_UNFOUND];
        }
        // 响应
        return [&#39;code&#39; => ErrorCode::SUCCESS, &#39;data&#39; => $data];
    }

}
Copy after login

Create error code class:

apps/index/messages/ErrorCode.php
Copy after login
<?php

namespace apps\index\messages;

class ErrorCode
{

    const SUCCESS = 0;
    const INVALID_PARAM = 100001;
    const ERROR_ID_UNFOUND = 200001;

}
Copy after login

Create a form validation model:

apps/index/models/ArticlesForm.php
Copy after login
<?php

namespace apps\index\models;

use mix\validators\Validator;
use apps\common\models\ArticlesModel;

class ArticlesForm extends Validator
{

    public $id;

    // 规则
    public function rules()
    {
        return [
            &#39;id&#39; => [&#39;integer&#39;, &#39;unsigned&#39; => true, &#39;maxLength&#39; => 10],
        ];
    }

    // 场景
    public function scenarios()
    {
        return [
            &#39;actionDetails&#39; => [&#39;required&#39; => [&#39;id&#39;]],
        ];
    }

    // 获取详情
    public function getDetails()
    {
        return (new ArticlesModel())->getRowById($this->id);
    }

}
Copy after login

Create a data table model:

apps/common/models/ArticlesModel.php
Copy after login
<?php

namespace apps\common\models;

use mix\facades\RDB;

class ArticlesModel
{

    const TABLE = &#39;articles&#39;;

    // 获取一行数据通过id
    public function getRowById($id)
    {
        $sql = "SELECT * FROM `" . self::TABLE . "` WHERE id = :id";
        $row = RDB::createCommand($sql)->bindParams([
            &#39;id&#39; => $id,
        ])->queryOne();
        return $row;
    }

}
Copy after login

The above is the writing of all the code.

Step 4

Use Postman to test, as follows:

How to use MixPHP to develop API interfaces

The interface development and testing is completed, isn’t it very simple?

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Swoole's Learning - Analysis of Asynchronous Tasks

Swoole's Learning - Introduction to Swoole

The above is the detailed content of How to use MixPHP to develop API interfaces. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!