前些時間用ucenter來做一個使用者登入系統,項目本身使用的是ThinkPHP架構,由於早期的PHP沒有命名空間的原因,於是Ucenter與ThinkPHP的代碼產生了衝突,具體是什麼衝突我沒有去細究,相信也沒有這個必要,反正我是證明了二者的代碼存在衝突就好了。
而我又不得不同時使用Ucenter和ThinkPHP,因此我需要一個解決方案,於是很自然地想到了,把對Ucenter的調用做成HTTP Service的形式,讓ThinkPHP與Ucenter通過HTTP協議來進行通訊,這就把二者的運行環境隔離開來了。
由於比較簡單,下面直接上代碼,不明白的可以回複評論提問。
<?php
// UClient 中介軟體通訊類
class UClientApi{
private function __call( $method, $args ){
// 使用 curl 擴充進行 HTTP 通訊
// ThinkPHP 項目設定檔需作以下配置:
// UCLIENT_URL UClient HTTP 服務的 URL
// UCLIENT_KEY UClient HTTP 服務的密鑰
$data = 'UCLIENT_KEY='.urlencode(C('UCLIENT_KEY')).'&method='.urlencode($method).'&args='.urlencode(base64_encode(serialize($args)));
$uclient_handle = curl_init( C('UCLIENT_URL') );
$opts = array(
CURLOPT_HEADER =>false,
CURLOPT_RETURNTRANSFER =>true,
CURLOPT_POST =>true,
CURLOPT_POSTFIELDS =>$data
);
curl_setopt_array( $uclient_handle, $opts );
$result = curl_exec( $uclient_handle );
return unserialize(base64_decode($result));
}
}
感歎一下PHP有多高效。
<?php
// Web Service 介面檔案
ob_start();
include './config.inc.php';
include './uc_client/client.php';
// 檢查密鑰,認證訪問身份
if ( empty($_POST['UCLIENT_KEY']) || $_POST['UCLIENT_KEY'] != UCLIENT_KEY) exit('Access denied.');
// 檢查調用的api是否存在
$method = 'uc_'.$_POST['method'];
if ( !function_exists( $method ) ) exit('Method is not exists.');
$args = unserialize(base64_decode($_POST['args']));
$exec_string = '$result='+$method.'(';
for ($i = 0; $i < count($args); $i++) $exec_string += '$args['+$i+']';
$exec_string += ');';
eval($exec_string);
ob_clean();
exit( base64_encode(serialize($result)) );