Table of Contents
PHP中Restful api 错误提示返回值实现思路,restfulapi
您可能感兴趣的文章:
Home php教程 php手册 PHP中Restful api 错误提示返回值实现思路,restfulapi

PHP中Restful api 错误提示返回值实现思路,restfulapi

Jun 13, 2016 am 08:42 AM
api restful return

PHP中Restful api 错误提示返回值实现思路,restfulapi

RESTful架构是一种流行的互联网软件架构,它结构清晰,符合标准,易于理解,扩展方便。

REST是Representational State Transfer的缩写,翻译为“表现层状态转化”。表现层其实就是资源,因此可以理解为“资源状态转化”。

网络应用上的任何实体都可以看作是一种资源,通过一个URI(统一资源定位符)指向它。

序言

不管是微博还是淘宝,他们都有自己的错误返回值格式规范,以及错误代码说明,这样不但手机端用起来方便,给人的感觉也清晰明了,高大上。遇到问题先找母本,大公司的规范就是我们参照的母本。为此,我仿照了淘宝的错误返回值格式,根据微博错误代码制定的标准自定了自己的错误代码,然后在Restful api 上进行测试。下面我将实现思路以及测试结果分享给大家。

实现思路

我利用抽象工厂模式去实现这样的一个错误返回值。选择这种模式是因为考虑到了这种模式可以提供一个创建一系列相关或相互依赖对象的接口,与我的需求很接近。

代码分析

1、按这个路径common\hint,我新建了个error文件夹存放我的错误提示程序文件。这文件夹中主要有这几个文件:

2、Hint.php入口文件。定义一个抽象类,里边只写一个方法。

interface Hint {
function Error($_errors,$code);
}
Copy after login

3、Template.php 实现Hint这个接口。错误返回值的格式就在这里定义。

class Template implements Hint{
function Error($_errors,$code) { 
if (empty($_errors)) {
print_r(json_encode([]));
} else { 
$errors['error']['name'] = 'Not Found';
$errors['error']['message'] = $_errors;
$errors['error']['error_code'] = $code; 
print_r(json_encode($errors));
}
}
}
Copy after login

4、createMsg.php 再创建一个createMsg抽象类。将对象的创建抽象成一个接口。

interface createMsg { 
function Msg(); 
}
Copy after login

5、用FactoryMsg 类去实现createMsg接口。返回实例化的Template。

class FactoryMsg implements createMsg{
function Msg() {
return new Template;
}
}
Copy after login

6、ErrorMsg.php 给Template里边的Error方法传参。

class ErrorMsg {
// 抽象工厂里的静态方法
public static function Info($_errors) { 
$Factory = new FactoryMsg;
$result = strstr($_errors,Yii::t('yii','Not exist')); //数据不存在 20001
$result1 = strstr($_errors,Yii::t('yii','Null')); //参数不能为空 20002
$result2 = strstr($_errors,Yii::t('yii','Fail')); //新增、更新、删除失败 20003
$result3 = strstr($_errors,Yii::t('yii','Not right')); //XX不正确 20004
$result4 = strstr($_errors,Yii::t('yii','Robc')); //XX无权限 20005
//数据不存在 20001
if(!empty($result)){ 
$M = $Factory->Msg();
$M->Error($_errors,'20001');die;
}
//参数不能为空 20002
if(!empty($result1)){ 
$M = $Factory->Msg();
$M->Error($_errors,'20002');die;
}
//新增、更新、删除失败 20003
if(!empty($result2)){ 
$M = $Factory->Msg();
$M->Error($_errors,'20003');die;
}
//XX不正确 20004
if(!empty($result3)){ 
$M = $Factory->Msg();
$M->Error($_errors,'20004');die;
}
//XX无权限 20005
if(!empty($result4)){ 
$M = $Factory->Msg();
$M->Error($_errors,'20005');die;
}
//默认类型 21000
$M = $Factory->Msg();
$M->Error($_errors,'21000');
}
}
Copy after login

7、调用方式。

use common\hint\error\ErrorMsg;
ErrorMsg::Info(Yii::t('yii','failure'));
Copy after login

8、测试结果。

{
"error": {
"name": "Not Found",
"message": "操作失败",
"error_code": "20003"
}
}
Copy after login

完成。整个实现过程我采用语言包的形式,这样有利于后期多语言的切换。

常见问题

1、采用这种字符串模糊搜索很泛,无法达到具体错误类型返回对应具体代码的要求。如有更好的建议,欢迎大家提议。

$result = strstr($_errors,Yii::t('yii','Not exist'));
Copy after login

2、实现过程中没有考虑到今后多语言切换的问题,然后直接用传统的方式传提示语。比如:ErrorMsg::Info("操作失败");这样是无法实现多语言切换的。建议大家用语言包的方式传参。

您可能感兴趣的文章:

  • PHP实现自动识别Restful API的返回内容类型
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP Tips: Quickly Implement Return to Previous Page Function PHP Tips: Quickly Implement Return to Previous Page Function Mar 09, 2024 am 08:21 AM

PHP Tips: Quickly implement the function of returning to the previous page. In web development, we often encounter the need to implement the function of returning to the previous page. Such operations can improve the user experience and make it easier for users to navigate between web pages. In PHP, we can achieve this function through some simple code. This article will introduce how to quickly implement the function of returning to the previous page and provide specific PHP code examples. In PHP, we can use $_SERVER['HTTP_REFERER'] to get the URL of the previous page

How to crawl and process data by calling API interface in PHP project? How to crawl and process data by calling API interface in PHP project? Sep 05, 2023 am 08:41 AM

How to crawl and process data by calling API interface in PHP project? 1. Introduction In PHP projects, we often need to crawl data from other websites and process these data. Many websites provide API interfaces, and we can obtain data by calling these interfaces. This article will introduce how to use PHP to call the API interface to crawl and process data. 2. Obtain the URL and parameters of the API interface. Before starting, we need to obtain the URL of the target API interface and the required parameters.

How to deal with Laravel API error problems How to deal with Laravel API error problems Mar 06, 2024 pm 05:18 PM

Title: How to deal with Laravel API error problems, specific code examples are needed. When developing Laravel, API errors are often encountered. These errors may come from various reasons such as program code logic errors, database query problems, or external API request failures. How to handle these error reports is a key issue. This article will use specific code examples to demonstrate how to effectively handle Laravel API error reports. 1. Error handling in Laravel

Oracle API Usage Guide: Exploring Data Interface Technology Oracle API Usage Guide: Exploring Data Interface Technology Mar 07, 2024 am 11:12 AM

Oracle is a world-renowned database management system provider, and its API (Application Programming Interface) is a powerful tool that helps developers easily interact and integrate with Oracle databases. In this article, we will delve into the Oracle API usage guide, show readers how to utilize data interface technology during the development process, and provide specific code examples. 1.Oracle

What results does MySQL return after inserting data? What results does MySQL return after inserting data? Mar 01, 2024 am 10:27 AM

MySQL is a widely used relational database management system for storing and managing data. When we want to insert new data into a database table, we usually use the INSERT statement. In MySQL, when the INSERT statement is executed to successfully insert data, a result will be returned, which is the result of the insertion operation. In this article, we will discuss in detail the results returned by MySQL after inserting data and provide some specific code examples. 1. The result returned after inserting data is in MySQL. When successfully executed

Oracle API integration strategy analysis: achieving seamless communication between systems Oracle API integration strategy analysis: achieving seamless communication between systems Mar 07, 2024 pm 10:09 PM

OracleAPI integration strategy analysis: To achieve seamless communication between systems, specific code examples are required. In today's digital era, internal enterprise systems need to communicate with each other and share data, and OracleAPI is one of the important tools to help achieve seamless communication between systems. This article will start with the basic concepts and principles of OracleAPI, explore API integration strategies, and finally give specific code examples to help readers better understand and apply OracleAPI. 1. Basic Oracle API

React API Call Guide: How to interact and transfer data with the backend API React API Call Guide: How to interact and transfer data with the backend API Sep 26, 2023 am 10:19 AM

ReactAPI Call Guide: How to interact with and transfer data to the backend API Overview: In modern web development, interacting with and transferring data to the backend API is a common need. React, as a popular front-end framework, provides some powerful tools and features to simplify this process. This article will introduce how to use React to call the backend API, including basic GET and POST requests, and provide specific code examples. Install the required dependencies: First, make sure Axi is installed in the project

Save API data to CSV format using Python Save API data to CSV format using Python Aug 31, 2023 pm 09:09 PM

In the world of data-driven applications and analytics, APIs (Application Programming Interfaces) play a vital role in retrieving data from various sources. When working with API data, you often need to store the data in a format that is easy to access and manipulate. One such format is CSV (Comma Separated Values), which allows tabular data to be organized and stored efficiently. This article will explore the process of saving API data to CSV format using the powerful programming language Python. By following the steps outlined in this guide, we will learn how to retrieve data from the API, extract relevant information, and store it in a CSV file for further analysis and processing. Let’s dive into the world of API data processing with Python and unlock the potential of the CSV format

See all articles