添加api接口的支持

This commit is contained in:
thinkphp
2015-05-12 15:34:04 +08:00
parent d886644b58
commit 36a84e75de
20 changed files with 247 additions and 196 deletions

View File

@@ -34,6 +34,7 @@ defined('VAR_CONTROLLER') OR define('VAR_CONTROLLER', 'c');
defined('VAR_ACTION') OR define('VAR_ACTION', 'a');
defined('APP_DEBUG') OR define('APP_DEBUG', false); // 是否调试模式
defined('ENV_PREFIX') OR define('ENV_PREFIX', 'T_'); // 环境变量的配置前缀
defined('IS_API') OR define('IS_API', false); // 是否API接口
// 应用模式 默认为普通模式
defined('APP_MODE') OR define('APP_MODE', function_exists('saeAutoLoader') ? 'sae' : 'common');
@@ -266,18 +267,3 @@ function S($name,$value='',$options=null) {
return $cache->set($name, $value, $expire);
}
}
/**
* 字符串命名风格转换
* type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
* @param string $name 字符串
* @param integer $type 转换类型
* @return string
*/
function parse_name($name, $type=0) {
if ($type) {
return ucfirst(preg_replace_callback('/_([a-zA-Z])/', function($match){ return strtoupper($match[1]);}, $name));
} else {
return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
}
}

View File

@@ -32,7 +32,9 @@ class App {
Cache::connect($config['cache']);
// 加载框架底层语言包
is_file(THINK_PATH.'Lang/'.strtolower($config['default_lang']).EXT) AND Lang::set(include THINK_PATH.'Lang/'.strtolower($config['default_lang']).EXT);
if(is_file(THINK_PATH.'Lang/'.strtolower($config['default_lang']).EXT)){
Lang::set(include THINK_PATH.'Lang/'.strtolower($config['default_lang']).EXT);
}
if(is_file(APP_PATH.'build.php')) { // 自动化创建脚本
Create::build(include APP_PATH.'build.php');
@@ -85,7 +87,7 @@ class App {
$action = ACTION_NAME . $config['action_suffix'];
}
if(!$instance) {
throw new Exception('[ ' . MODULE_NAME . '\\'.CONTROLLER_LAYER.'\\' . parse_name(CONTROLLER_NAME, 1) . ' ] not exists');
throw new Exception('[ ' . MODULE_NAME . '\\'.CONTROLLER_LAYER.'\\' . Loader::parseName(CONTROLLER_NAME, 1) . ' ] not exists');
}
try{
@@ -122,16 +124,20 @@ class App {
}elseif($param->isDefaultValueAvailable()){
$args[] = $param->getDefaultValue();
}else{
E('_PARAM_ERROR_:' . $name);
throw new Exception('_PARAM_ERROR_:' . $name);
}
}
array_walk_recursive($args,'Input::filterExp');
$method->invokeArgs($instance, $args);
$data = $method->invokeArgs($instance, $args);
}else{
$method->invoke($instance);
$data = $method->invoke($instance);
}
// 操作方法执行完成监听
Hook::listen('action_end', $call);
if(IS_API){
// API接口返回数据
self::returnData($data,$config['default_ajax_return']);
}
}else{
// 操作方法不是Public 抛出异常
throw new \ReflectionException();
@@ -150,6 +156,44 @@ class App {
return ;
}
/**
* 返回API数据到客户端
* @access protected
* @param mixed $data 要返回的数据
* @param String $type 返回数据格式
* @return void
*/
static public function returnData($data, $type='') {
$headers = [
'json' => 'application/json',
'xml' => 'text/xml',
'jsonp' => 'application/javascript',
'script'=> 'application/javascript',
'text' => 'text/plain',
];
$type = strtolower($type);
if(isset($headers[$type])){
header('Content-Type:'.$headers[$type].'; charset=utf-8');
}
switch ($type){
case 'json':
// 返回JSON数据格式到客户端 包含状态信息
$data = Transform::jsonEncode($data);
break;
case 'xml':
// 返回xml格式数据
$data = Transform::xmlEncode($data);
break;
case 'jsonp':
// 返回JSON数据格式到客户端 包含状态信息
$handler = isset($_GET[Config::get('var_jsonp_handler')]) ? $_GET[Config::get('var_jsonp_handler')] : Config::get('default_jsonp_handler');
$data = $handler . '(' . Transform::jsonEncode($data) . ');';
break;
}
exit($data);
}
/**
* 初始化模块
* @access private

View File

@@ -10,6 +10,7 @@
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Exception;
/**
* Apc缓存驱动
@@ -30,7 +31,7 @@ class Apc {
*/
public function __construct($options=[]) {
if(!function_exists('apc_cache_info')) {
E('_NOT_SUPPERT_:Apc');
throw new Exception('_NOT_SUPPERT_:Apc');
}
if(!empty($options)) {
$this->options = array_merge($this->options,$options);

View File

@@ -10,6 +10,7 @@
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Exception;
/**
* Memcache缓存驱动
@@ -33,7 +34,7 @@ class Memcache {
*/
public function __construct($options=[]) {
if ( !extension_loaded('memcache') ) {
E('_NOT_SUPPERT_:memcache');
throw new Exception('_NOT_SUPPERT_:memcache');
}
if(!empty($options)) {
$this->options = array_merge($this->options,$options);

View File

@@ -10,6 +10,7 @@
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Exception;
/**
* Redis缓存驱动
@@ -34,7 +35,7 @@ class Redis {
*/
public function __construct($options=[]) {
if ( !extension_loaded('redis') ) {
E('_NOT_SUPPERT_:redis');
throw new Exception('_NOT_SUPPERT_:redis');
}
if(!empty($options)) {
$this->options = array_merge($this->options,$options);

View File

@@ -10,6 +10,7 @@
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Exception;
/**
* Sqlite缓存驱动
@@ -33,7 +34,7 @@ class Sqlite {
*/
public function __construct($options=[]) {
if ( !extension_loaded('sqlite') ) {
E('_NOT_SUPPERT_:sqlite');
throw new Exception('_NOT_SUPPERT_:sqlite');
}
if(!empty($options)) {
$this->options = array_merge($this->options,$options);

View File

@@ -10,6 +10,7 @@
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Exception;
/**
* Wincache缓存驱动
@@ -30,7 +31,7 @@ class Wincache {
*/
public function __construct($options=[]) {
if ( !function_exists('wincache_ucache_info') ) {
E('_NOT_SUPPERT_:WinCache');
throw new Exception('_NOT_SUPPERT_:WinCache');
}
if(!empty($options)) {
$this->options = array_merge($this->options,$options);

View File

@@ -10,6 +10,7 @@
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Exception;
/**
* Xcache缓存驱动
@@ -30,7 +31,7 @@ class Xcache {
*/
public function __construct($options=[]) {
if ( !function_exists('xcache_info') ) {
E('_NOT_SUPPERT_:Xcache');
throw new Exception('_NOT_SUPPERT_:Xcache');
}
if(!empty($options)) {
$this->options = array_merge($this->options,$options);

View File

@@ -30,6 +30,7 @@ class Controller {
$this->_initialize();
}
// 前置操作方法
// 支持 ['action1','action2'] 或者 ['action1'=>['only'=>'index'],'action2'=>'except'=>'login']
$list = Config::get('before_action_list');
if($list){
foreach($list as $method=>$options){
@@ -100,50 +101,32 @@ class Controller {
return $this->assign($name, $value);
}
/**
* 返回API数据到客户端
* @access protected
* @param mixed $data 要返回的数据
* @param integer $code 返回的code
* @param mixed $msg 提示信息
* @param string $type 返回数据格式
* @return void
*/
protected function result($data,$code=0,$msg='',$type='') {
$result['code'] = $code;
$result['msg'] = $msg;
$result['time'] = NOW_TIME;
$result['data'] = $data;
app::returnData($result,$type);
}
/**
* Ajax方式返回数据到客户端
* @access protected
* @param mixed $data 要返回的数据
* @param String $type AJAX返回数据格式
* @param mixed $fun 数据处理方法
* @return void
*/
protected function ajaxReturn($data, $type='',$fun='') {
if(empty($type)) {
$type = Config::get('default_ajax_return');
}
$headers = [
'json' => 'application/json',
'xml' => 'text/xml',
'jsonp' => 'application/javascript',
'script'=> 'application/javascript',
'html' => 'text/html',
'text' => 'text/plain',
];
$type = strtolower($type);
if(isset($headers[$type])){
header('Content-Type:'.$headers[$type].'; charset=utf-8');
}
if($fun && is_callable($fun)){
$data = call_user_func($fun,$data);
}else{
switch ($type){
case 'json':
// 返回JSON数据格式到客户端 包含状态信息
$data = Transform::jsonEncode($data);
break;
case 'xml':
// 返回xml格式数据
$data = Transform::xmlEncode($data);
break;
case 'jsonp':
// 返回JSON数据格式到客户端 包含状态信息
$handler = isset($_GET[Config::get('var_jsonp_handler')]) ? $_GET[Config::get('var_jsonp_handler')] : Config::get('default_jsonp_handler');
$data = $handler . '(' . Transform::jsonEncode($data) . ');';
break;
}
}
exit($data);
protected function ajaxReturn($data, $type='') {
app::returnData($data,$type);
}
/**

View File

@@ -68,7 +68,7 @@ abstract class rest {
$this->$fun();
}else{
// 抛出异常
E(L('_ERROR_ACTION_:').ACTION_NAME);
throw new \think\Exception(L('_ERROR_ACTION_:').ACTION_NAME);
}
}

View File

@@ -10,9 +10,10 @@
// +----------------------------------------------------------------------
namespace think\db;
use think\config;
use think\debug;
use think\log;
use think\Config;
use think\Debug;
use think\Log;
use think\Exception;
use PDO;
abstract class Driver {
@@ -101,7 +102,7 @@ abstract class Driver {
Log::record($e->getMessage(),'ERR');
return $this->connect($autoConnection,$linkNum);
}elseif($config['debug']){
E($e->getMessage());
throw new Exception($e->getMessage());
}
}
}
@@ -161,15 +162,15 @@ abstract class Driver {
}
$this->bind = [];
try{
$result = $this->PDOStatement->execute();
// 调试结束
$this->debug(false);
if ( false === $result ) {
$this->error();
return false;
} else {
return $this->getResult();
}
$result = $this->PDOStatement->execute();
// 调试结束
$this->debug(false);
if ( false === $result ) {
$this->error();
return false;
} else {
return $this->getResult();
}
}catch (\PDOException $e) {
$this->error();
return false;
@@ -214,18 +215,18 @@ abstract class Driver {
}
$this->bind = [];
try{
$result = $this->PDOStatement->execute();
$this->debug(false);
if ( false === $result) {
$this->error();
return false;
} else {
$this->numRows = $this->PDOStatement->rowCount();
if(preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $str)) {
$this->lastInsID = $this->_linkID->lastInsertId();
}
return $this->numRows;
}
$result = $this->PDOStatement->execute();
$this->debug(false);
if ( false === $result) {
$this->error();
return false;
} else {
$this->numRows = $this->PDOStatement->rowCount();
if(preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $str)) {
$this->lastInsID = $this->_linkID->lastInsertId();
}
return $this->numRows;
}
}catch (\PDOException $e) {
$this->error();
return false;
@@ -341,7 +342,7 @@ abstract class Driver {
// 记录错误日志
Log::record($this->error,'ERR');
if($this->config['debug']) {// 开启数据库调试模式
E($this->error);
throw new Exception($this->error);
}else{
return $this->error;
}
@@ -505,10 +506,6 @@ abstract class Driver {
// 解析特殊条件表达式
$whereStr .= $this->parseThinkWhere($key,$val);
}else{
// 查询字段的安全过滤
// if(!preg_match('/^[A-Z_\|\&\-.a-z0-9\(\)\,]+$/',trim($key))){
// E(L('_EXPRESS_ERROR_').':'.$key);
// }
// 多条件支持
$multi = is_array($val) && isset($val['_multi']);
$key = trim($key);
@@ -578,7 +575,7 @@ abstract class Driver {
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
$whereStr .= $key.' '.$this->exp[$exp].' '.$this->parseValue($data[0]).' AND '.$this->parseValue($data[1]);
}else{
E(L('_EXPRESS_ERROR_').':'.$val[0]);
throw new Exception(L('_EXPRESS_ERROR_').':'.$val[0]);
}
}else {
$count = count($val);

View File

@@ -11,7 +11,7 @@
namespace think\db\driver;
use think\db\Driver;
use think\Exception;
/**
* Mongo数据库驱动
*/
@@ -31,7 +31,7 @@ class Mongo extends Driver {
*/
public function __construct($config=''){
if ( !class_exists('mongoClient') ) {
E(L('_NOT_SUPPERT_').':Mongo');
throw new Exception(L('_NOT_SUPPERT_').':Mongo');
}
if(!empty($config)) {
$this->config = array_merge($this->config,$config);
@@ -52,7 +52,7 @@ class Mongo extends Driver {
try{
$this->linkID[$linkNum] = new \mongoClient( $host,$this->config['params']);
}catch (\MongoConnectionException $e){
E($e->getmessage());
throw new Exception($e->getmessage());
}
}
return $this->linkID[$linkNum];
@@ -86,8 +86,8 @@ class Mongo extends Driver {
$this->debug(false);
$this->_collectionName = $collection; // 记录当前Collection名称
}
}catch (MongoException $e){
E($e->getMessage());
}catch (\MongoException $e){
throw new Exception($e->getMessage());
}
}
@@ -112,7 +112,7 @@ class Mongo extends Driver {
$result = $this->_mongo->command($command);
$this->debug(false);
if(!$result['ok']) {
E($result['errmsg']);
throw new Exception($result['errmsg']);
}
return $result;
}
@@ -133,7 +133,7 @@ class Mongo extends Driver {
if($result['ok']) {
return $result['retval'];
}else{
E($result['errmsg']);
throw new Exception($result['errmsg']);
}
}
@@ -194,7 +194,7 @@ class Mongo extends Driver {
}
return $result;
} catch (\MongoCursorException $e) {
E($e->getMessage());
throw new Exception($e->getMessage());
}
}
@@ -217,7 +217,7 @@ class Mongo extends Driver {
$this->debug(false);
return $result;
} catch (\MongoCursorException $e) {
E($e->getMessage());
throw new Exception($e->getMessage());
}
}
@@ -236,7 +236,7 @@ class Mongo extends Driver {
$result = $this->_collection->find([],[$pk=>1])->sort([$pk=>-1])->limit(1);
$this->debug(false);
} catch (\MongoCursorException $e) {
E($e->getMessage());
throw new Exception($e->getMessage());
}
$data = $result->getNext();
return isset($data[$pk])?$data[$pk]+1:1;
@@ -273,7 +273,7 @@ class Mongo extends Driver {
$this->debug(false);
return $result;
} catch (\MongoCursorException $e) {
E($e->getMessage());
throw new Exception($e->getMessage());
}
}
@@ -299,7 +299,7 @@ class Mongo extends Driver {
$this->debug(false);
return $result;
} catch (\MongoCursorException $e) {
E($e->getMessage());
throw new Exception($e->getMessage());
}
}
@@ -324,7 +324,7 @@ class Mongo extends Driver {
$this->debug(false);
return $result;
} catch (\MongoCursorException $e) {
E($e->getMessage());
throw new Exception($e->getMessage());
}
}
@@ -398,7 +398,7 @@ class Mongo extends Driver {
}
return $resultSet;
} catch (\MongoCursorException $e) {
E($e->getMessage());
throw new Exception($e->getMessage());
}
}
@@ -439,7 +439,7 @@ class Mongo extends Driver {
}
return $result;
} catch (\MongoCursorException $e) {
E($e->getMessage());
throw new Exception($e->getMessage());
}
}
@@ -467,7 +467,7 @@ class Mongo extends Driver {
$this->debug(false);
return $count;
} catch (\MongoCursorException $e) {
E($e->getMessage());
throw new Exception($e->getMessage());
}
}
@@ -493,7 +493,7 @@ class Mongo extends Driver {
$result = $this->_collection->findOne();
$this->debug(false);
} catch (\MongoCursorException $e) {
E($e->getMessage());
throw new Exception($e->getMessage());
}
if($result) { // 存在数据则分析字段
$info = [];
@@ -631,7 +631,7 @@ class Mongo extends Driver {
}else{
// 查询字段的安全过滤
if(!preg_match('/^[A-Z_\|\&\-.a-z0-9]+$/',trim($key))){
E(L('_ERROR_QUERY_').':'.$key);
throw new Exception(L('_ERROR_QUERY_').':'.$key);
}
$key = trim($key);
if(strpos($key,'|')) {

View File

@@ -59,19 +59,25 @@ class Oracle extends Driver{
$this->debug(true);
$this->PDOStatement = $this->_linkID->prepare($str);
if(false === $this->PDOStatement) {
E($this->error());
}
$result = $this->PDOStatement->execute($bind);
$this->debug(false);
if ( false === $result) {
$this->error();
return false;
} else {
$this->numRows = $this->PDOStatement->rowCount();
if($flag || preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $str)) {
$this->lastInsID = $this->_linkID->lastInsertId();
}
try{
$result = $this->PDOStatement->execute($bind);
$this->debug(false);
if ( false === $result) {
$this->error();
return false;
} else {
$this->numRows = $this->PDOStatement->rowCount();
if($flag || preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $str)) {
$this->lastInsID = $this->_linkID->lastInsertId();
}
return $this->numRows;
}
return $this->numRows;
}catch (\PDOException $e) {
$this->error();
return false;
}
}
@@ -129,7 +135,7 @@ class Oracle extends Driver{
* @access public
* @return string
*/
public function parseLimit($limit) {
public function parseLimit($limit) {
$limitStr = '';
if(!empty($limit)) {
$limit = explode(',',$limit);

View File

@@ -90,11 +90,11 @@ class Lite {
if(empty($config)) $config = $this->config;
try{
if(empty($config['dsn'])) {
E('Think/Db/Lite 必须设置 dsn参数');
throw new Exception('Think/Db/Lite 必须设置 dsn参数');
}
$this->linkID[$linkNum] = new PDO( $config['dsn'], $config['username'], $config['password'],$config['params']);
}catch (\PDOException $e) {
E($e->getMessage());
throw new Exception($e->getMessage());
}
}
return $this->linkID[$linkNum];
@@ -128,8 +128,10 @@ class Lite {
// 调试开始
$this->debug(true);
$this->PDOStatement = $this->_linkID->prepare($str);
if(false === $this->PDOStatement)
E($this->error());
if(false === $this->PDOStatement){
$this->error();
return false;
}
foreach ($bind as $key => $val) {
if(is_array($val)){
$this->PDOStatement->bindValue($key, $val[0], $val[1]);
@@ -137,14 +139,19 @@ class Lite {
$this->PDOStatement->bindValue($key, $val);
}
}
$result = $this->PDOStatement->execute();
// 调试结束
$this->debug(false);
if ( false === $result ) {
try{
$result = $this->PDOStatement->execute();
// 调试结束
$this->debug(false);
if ( false === $result ) {
$this->error();
return false;
} else {
return $this->getResult();
}
}catch (\PDOException $e) {
$this->error();
return false;
} else {
return $this->getResult();
}
}
@@ -168,8 +175,9 @@ class Lite {
// 记录开始执行时间
$this->debug(true);
$this->PDOStatement = $this->_linkID->prepare($str);
if(false === $this->PDOStatement) {
E($this->error());
if(false === $this->PDOStatement){
$this->error();
return false;
}
foreach ($bind as $key => $val) {
if(is_array($val)){
@@ -178,17 +186,22 @@ class Lite {
$this->PDOStatement->bindValue($key, $val);
}
}
$result = $this->PDOStatement->execute();
$this->debug(false);
if ( false === $result) {
try{
$result = $this->PDOStatement->execute();
$this->debug(false);
if ( false === $result) {
$this->error();
return false;
} else {
$this->numRows = $this->PDOStatement->rowCount();
if(preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $str)) {
$this->lastInsID = $this->_linkID->lastInsertId();
}
return $this->numRows;
}
}catch (\PDOException $e) {
$this->error();
return false;
} else {
$this->numRows = $this->PDOStatement->rowCount();
if(preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $str)) {
$this->lastInsID = $this->_linkID->lastInsertId();
}
return $this->numRows;
}
}
@@ -300,7 +313,7 @@ class Lite {
// 记录错误日志
Log::record($this->error,'ERR');
if($this->config['debug']) {// 开启数据库调试模式
E($this->error);
throw new Exception($this->error);
}else{
return $this->error;
}

View File

@@ -18,19 +18,13 @@ class Error {
* @param mixed $e 异常对象
*/
static public function appException($e) {
$error = [];
$error['message'] = $e->getMessage();
$trace = $e->getTrace();
if('E' == $trace[0]['function']) {
$error['file'] = $trace[0]['file'];
$error['line'] = $trace[0]['line'];
}else{
$error['file'] = $e->getFile();
$error['line'] = $e->getLine();
}
$error['trace'] = $e->getTraceAsString();
$error['message'] = $e->getMessage();
$error['file'] = $e->getFile();
$error['line'] = $e->getLine();
$error['trace'] = $e->getTraceAsString();
$error['code'] = $e->getCode();
// 记录异常日志
Log::record($error['message'],'ERR');
Log::record($error['message'],'ERR');
// 发送404信息
header('HTTP/1.1 404 Not Found');
header('Status:404 Not Found');
@@ -50,10 +44,6 @@ class Error {
static public function appError($errno, $errstr, $errfile, $errline) {
$errorStr = "[{$errno}] {$errstr} {$errfile}{$errline} 行.";
switch ($errno) {
case E_ERROR:
case E_PARSE:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
Log::record($errorStr, 'ERROR');
self::halt($errorStr);
@@ -94,22 +84,32 @@ class Error {
* @return void
*/
static public function halt($error) {
IS_CLI && exit(is_array($error)?$error['message']:$error);
$message = is_array($error)? $error['message'] : $error;
$code = is_array($error)? $error['code'] : 1;
if(IS_CLI){
exit($message);
}elseif(IS_API){
// API接口
$data['code'] = $code;
$data['msg'] = $message;
$data['time'] = NOW_TIME;
app::returnData($data);
}
$e = [];
if (APP_DEBUG) {
//调试模式下输出错误信息
if (!is_array($error)) {
$trace = debug_backtrace();
$e['message'] = $error;
$e['file'] = $trace[0]['file'];
$e['line'] = $trace[0]['line'];
$trace = debug_backtrace();
$e['message'] = $error;
$e['file'] = $trace[0]['file'];
$e['line'] = $trace[0]['line'];
ob_start();
debug_print_backtrace();
$e['trace'] = ob_get_clean();
$e['trace'] = ob_get_clean();
} else {
$e = $error;
}
} else {
}else {
//否则定向到错误页面
$error_page = Config::get('error_page');
if (!empty($error_page)) {

View File

@@ -139,7 +139,7 @@ class Loader {
}else{
$module = MODULE_NAME;
}
$class = $module . '\\' . $layer . '\\' . parse_name($name, 1);
$class = $module . '\\' . $layer . '\\' . self::parseName($name, 1);
if(class_exists($class)) {
$model = new $class($name);
}else {
@@ -166,7 +166,7 @@ class Loader {
}else{
$module = MODULE_NAME;
}
$class = $module . '\\' . $layer . '\\' . parse_name($name, 1) ;
$class = $module . '\\' . $layer . '\\' . self::parseName($name, 1) ;
if(class_exists($class)) {
$action = new $class;
$_instance[$name . $layer] = $action;
@@ -233,4 +233,19 @@ class Loader {
}
return $_instance[$identify];
}
/**
* 字符串命名风格转换
* type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
* @param string $name 字符串
* @param integer $type 转换类型
* @return string
*/
static public function parseName($name, $type=0) {
if ($type) {
return ucfirst(preg_replace_callback('/_([a-zA-Z])/', function($match){ return strtoupper($match[1]);}, $name));
} else {
return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
}
}
}

View File

@@ -751,7 +751,7 @@ class Model {
if(!empty($this->tableName)) {
$tableName .= $this->tableName;
}else{
$tableName .= parse_name($this->name);
$tableName .= Loader::parseName($this->name);
}
$this->trueTableName = strtolower($tableName);
}
@@ -919,7 +919,7 @@ class Model {
}elseif(is_string($data)){
parse_str($data,$data);
}elseif(!is_array($data)){
E(Lang::get('_DATA_TYPE_INVALID_'));
throw new Exception(Lang::get('_DATA_TYPE_INVALID_'));
}
$this->data = $data;
return $this;
@@ -976,7 +976,7 @@ class Model {
$options = $union;
}
}else{
E(Lang::get('_DATA_TYPE_INVALID_'));
throw new Exception(Lang::get('_DATA_TYPE_INVALID_'));
}
$this->options['union'][] = $options;
return $this;

View File

@@ -9,6 +9,7 @@
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\model;
use think\Loader;
/**
* MongoModel模型类
@@ -39,16 +40,16 @@ class MongoModel extends \Think\Model{
public function __call($method,$args) {
if(strtolower(substr($method,0,5))=='getby') {
// 根据某个字段获取记录
$field = parse_name(substr($method,5));
$field = Loader::parseName(substr($method,5));
$where[$field] =$args[0];
return $this->where($where)->find();
}elseif(strtolower(substr($method,0,10))=='getfieldby') {
// 根据某个字段获取记录的某个值
$name = parse_name(substr($method,10));
$name = Loader::parseName(substr($method,10));
$where[$name] =$args[0];
return $this->where($where)->getField($args[1]);
}else{
throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
throw new \think\Exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
return;
}
}
@@ -266,7 +267,7 @@ class MongoModel extends \Think\Model{
if(!empty($this->tableName)) {
$tableName .= $this->tableName;
}else{
$tableName .= parse_name($this->name);
$tableName .= Loader::parseName($this->name);
}
$this->trueTableName = strtolower($tableName);
}

View File

@@ -15,7 +15,7 @@ class Url {
/**
* URL组装 支持不同URL模式
* @param string $url URL表达式格式'[分组/模块/操作#锚点@域名]?参数1=值1&参数2=值2...'
* @param string $url URL表达式格式'[模块/控制器/操作#锚点@域名]?参数1=值1&参数2=值2...'
* @param string|array $vars 传入的参数,支持数组和字符串
* @param string $suffix 伪静态后缀默认为true表示获取配置值
* @param boolean $domain 是否显示域名
@@ -24,31 +24,31 @@ class Url {
static public function build($url='',$vars='',$suffix=true,$domain=false) {
$config = Config::get();
// 解析URL
$info = parse_url($url);
$url = !empty($info['path'])?$info['path']:ACTION_NAME;
$info = parse_url($url);
$url = !empty($info['path'])?$info['path']:ACTION_NAME;
if(isset($info['fragment'])) { // 解析锚点
$anchor = $info['fragment'];
if(false !== strpos($anchor,'?')) { // 解析参数
list($anchor,$info['query']) = explode('?',$anchor,2);
list($anchor,$info['query']) = explode('?',$anchor,2);
}
if(false !== strpos($anchor,'@')) { // 解析域名
list($anchor,$host) = explode('@',$anchor, 2);
list($anchor,$host) = explode('@',$anchor, 2);
}
}elseif(false !== strpos($url,'@')) { // 解析域名
list($url,$host) = explode('@',$info['path'], 2);
}
// 解析子域名
if(isset($host)) {
$domain = $host.(strpos($host,'.')?'':strstr($_SERVER['HTTP_HOST'],'.'));
$domain = $host.(strpos($host,'.')?'':strstr($_SERVER['HTTP_HOST'],'.'));
}elseif($domain===true){
$domain = $_SERVER['HTTP_HOST'];
if($config['app_sub_domain_deplay'] ) { // 开启子域名部署
$domain = $domain=='localhost'?'localhost':'www'.strstr($_SERVER['HTTP_HOST'],'.');
$domain = $domain == 'localhost' ? 'localhost' : 'www'.strstr($_SERVER['HTTP_HOST'],'.');
// '子域名'=>array('项目[/分组]');
foreach ($config['app_sub_domain_rules'] as $key => $rule) {
if(false === strpos($key,'*') && 0=== strpos($url,$rule[0])) {
$domain = $key.strstr($domain,'.'); // 生成对应子域名
$url = substr_replace($url,'',0,strlen($rule[0]));
$domain = $key.strstr($domain,'.'); // 生成对应子域名
$url = substr_replace($url,'',0,strlen($rule[0]));
break;
}
}
@@ -79,16 +79,16 @@ class Url {
if('/' != $depr) { // 安全替换
$url = str_replace('/',$depr,$url);
}
// 解析分组、模块和操作
// 解析模块、控制器和操作
$url = trim($url,$depr);
$path = explode($depr,$url);
$var = [];
$var[VAR_ACTION] = !empty($path)?array_pop($path):ACTION_NAME;
$var[VAR_ACTION] = !empty($path)? array_pop($path) : ACTION_NAME;
if(!defined('BIND_CONTROLLER')){
$var[VAR_CONTROLLER] = !empty($path)?array_pop($path):CONTROLLER_NAME;
$var[VAR_CONTROLLER] = !empty($path)? array_pop($path) : CONTROLLER_NAME;
}
if(!defined('BIND_MODULE')){
$var[VAR_MODULE] = !empty($path)?array_pop($path):MODULE_NAME;
$var[VAR_MODULE] = !empty($path)? array_pop($path) : MODULE_NAME;
}
}
}
@@ -124,7 +124,7 @@ class Url {
$url .= '#'.$anchor;
}
if($domain) {
$url = (self::is_ssl()?'https://':'http://').$domain.$url;
$url = (self::is_ssl()? 'https://' : 'http://' ).$domain.$url;
}
return $url;
}

View File

@@ -10,7 +10,7 @@
// +----------------------------------------------------------------------
namespace traits\think\model;
use think\Loader;
trait Extend {
protected $partition = [];
@@ -29,18 +29,18 @@ trait Extend {
return $this->getField(strtoupper($method).'('.$field.') AS tp_'.$method);
}elseif(strtolower(substr($method,0,5))=='getby') {
// 根据某个字段获取记录
$field = parse_name(substr($method,5));
$field = Loader::parseName(substr($method,5));
$where[$field] = $args[0];
return $this->where($where)->find();
}elseif(strtolower(substr($method,0,10))=='getfieldby') {
// 根据某个字段获取记录的某个值
$name = parse_name(substr($method,10));
$name = Loader::parseName(substr($method,10));
$where[$name] =$args[0];
return $this->where($where)->getField($args[1]);
}elseif(isset($this->scope[$method])){// 命名范围的单独调用支持
return $this->scope($method,$args[0]);
}else{
E(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
throw new \think\Exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
return;
}
}