詳看JSON字符串在PHP中的應(yīng)用說明及技巧
JSON為何物?我就不重復(fù)概念了。通俗的說,它是一種數(shù)據(jù)的存儲格式,就像PHP序列化后的字符串一樣,只不過他搭建的是客戶端Javascript和服務(wù)端PHP的交互橋梁。我們用PHP生成JSON字符串。
以下4段代碼為我在JSON字符串項(xiàng)目中的簡單應(yīng)用(非生產(chǎn)環(huán)境),不健壯也不美化,但該SNS項(xiàng)目早已經(jīng)夭折。
1、異常類的層級關(guān)系:
- class NotFoundException extends Exception{}
- class InputException extends Exception{} class DBException extends Exception{}
2、配置未捕捉異常的處理器:
- function exception_uncaught_handler(Exception $e) { header('Content-type:text/html; charset=utf-8');
- if ($e instanceof NotFoundException) exit($e->getMessage()); elseif ($e instanceof DBException)
- exit($e->getMessage()); else exit($e->getMessage()); } set_exception_handler('exception_uncaught_handler');
3、在數(shù)據(jù)庫連接代碼,手動(dòng)拋出DBException異常但未使用try…catch進(jìn)行捕獲處理,該異常將被PHP自定義異常處理器exception_uncaught_handler()函數(shù)處理:
- $this->resConn = mysql_connect ($CONFIGS['db_host'], $CONFIGS['db_user'], $CONFIGS['db_pwd']);
- if (false == is_resource($this->resConn))
- throw new DBException('數(shù)據(jù)庫連接失敗。'.mysql_error($this->resConn));
4、JSON字符串業(yè)務(wù)邏輯一瞥:
- if (0 != strcmp($curAlbum->interest_id, $it)) throw new NotFoundException('很抱歉,你所訪問的相冊不存在');