本文已經作了更為詳細的解析:請移步 UCENTER UC_CLIENT調用時代碼沖突解決方案:改用HTTP方式調用,實現代碼隔離 http://www.snblog.cn/archives/70
前些時間用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)) );