|
发表于 2013-10-16 17:52:27
|
显示全部楼层
你看下面可否, 通过 $this->load->service('user_service');来调用。
也可以让所有的service集成一个common service, common service实现__get魔术方法获取CI对象的属性和方法。
也就和控制器一样方便了, 至于怎么划分service, 那就要个人功力了。
PHP复制代码
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Loader extends CI_Loader
{
protected $_ci_service_paths;
public function __construct ()
{
parent ::__construct ();
$this->_ci_service_paths = array(APPPATH .'/service');
}
public function service ($service_name = '', $params = NULL, $object_name = NULL)
{
if(is_array($service_name)) {
foreach($service_name as $class) {
$this->service($class, $params);
}
return;
}
if($service_name == '' or isset($this->_base_classes [$service_name])) {
return FALSE;
}
if(! is_null($params) && ! is_array($params)) {
$params = NULL;
}
$this->_ci_load_user_class ($service_name, $params, $object_name, $this->_ci_service_paths );
}
public function _ci_load_user_class ($class = '', $params = NULL, $object_name = NULL, $class_path = array(APPPATH ))
{
$class = str_replace('.php', '', trim($class, '/'));
$subdir = '';
if (($last_slash = strrpos($class, '/')) !== FALSE) {
$subdir = substr($class, 0, $last_slash + 1);
$class = substr($class, $last_slash + 1);
}
foreach (array(ucfirst($class), strtolower($class)) as $class) {
$is_duplicate = FALSE;
foreach ($class_path as $path) {
$filepath = $path.'/'.$subdir.$class.'.php';
if ( ! file_exists($filepath)) {
continue;
}
if (in_array($filepath, $this->_ci_loaded_files )) {
if ( ! is_null($object_name)) {
$CI =& get_instance ();
if ( ! isset($CI->$object_name)) {
return $this->_ci_init_class ($class, '', $params, $object_name);
}
}
$is_duplicate = TRUE;
log_message ('debug', $class." class already loaded. Second attempt ignored.");
return;
}
include_once($filepath);
$this->_ci_loaded_files [] = $filepath;
return $this->_ci_init_class ($class, '', $params, $object_name);
}
}
if ($is_duplicate == FALSE) {
log_message ('error', "Unable to load the requested class: ".$class);
show_error ("Unable to load the requested class: ".$class);
}
}
}
/* End of file MY_Controller.php */
/* Location: ./application/core/MY_Controller.php */
复制代码 |
|