RESTful架構是一種流行的互聯網軟件架構,它結構清晰,符合標準,易于理解,擴展方便。
REST是Representational State Transfer的縮寫,翻譯為“表現層狀態轉化”。表現層其實就是資源,因此可以理解為“資源狀態轉化”。
網絡應用上的任何實體都可以看作是一種資源,通過一個URI(統一資源定位符)指向它。
序言
不管是微博還是淘寶,他們都有自己的錯誤返回值格式規范,以及錯誤代碼說明,這樣不但手機端用起來方便,給人的感覺也清晰明了,高大上。遇到問題先找母本,大公司的規范就是我們參照的母本。為此,我仿照了淘寶的錯誤返回值格式,根據微博錯誤代碼制定的標準自定了自己的錯誤代碼,然后在Restful api 上進行測試。下面我將實現思路以及測試結果分享給大家。
實現思路
我利用抽象工廠模式去實現這樣的一個錯誤返回值。選擇這種模式是因為考慮到了這種模式可以提供一個創建一系列相關或相互依賴對象的接口,與我的需求很接近。
代碼分析
1、按這個路徑common\hint,我新建了個error文件夾存放我的錯誤提示程序文件。這文件夾中主要有這幾個文件:
2、Hint.php入口文件。定義一個抽象類,里邊只寫一個方法。
1
2
3
|
interface Hint { function Error( $_errors , $code ); } |
3、Template.php 實現Hint這個接口。錯誤返回值的格式就在這里定義。
1
2
3
4
5
6
7
8
9
10
11
12
|
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 )); } } } |
4、createMsg.php 再創建一個createMsg抽象類。將對象的創建抽象成一個接口。
1
2
3
|
interface createMsg { function Msg(); } |
5、用FactoryMsg 類去實現createMsg接口。返回實例化的Template。
1
2
3
4
5
|
class FactoryMsg implements createMsg{ function Msg() { return new Template; } } |
6、ErrorMsg.php 給Template里邊的Error方法傳參。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
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' ); } } |
7、調用方式。
1
2
|
use common\hint\error\ErrorMsg; ErrorMsg::Info(Yii::t( 'yii' , 'failure' )); |
8、測試結果。
1
2
3
4
5
6
7
|
{ "error" : { "name" : "Not Found" , "message" : "操作失敗" , "error_code" : "20003" } } |
完成。整個實現過程我采用語言包的形式,這樣有利于后期多語言的切換。
常見問題
1、采用這種字符串模糊搜索很泛,無法達到具體錯誤類型返回對應具體代碼的要求。如有更好的建議,歡迎大家提議。
1
|
$result = strstr ( $_errors ,Yii::t( 'yii' , 'Not exist' )); |
2、實現過程中沒有考慮到今后多語言切換的問題,然后直接用傳統的方式傳提示語。比如:ErrorMsg::Info("操作失敗");這樣是無法實現多語言切換的。建議大家用語言包的方式傳參。