CI MVC层级的扩展,更好的分离业务逻辑
向大家请教个问题:之前使用Java编程语言的时候,会使用View->controller->services->model的分层结构。
而现在CI中,只提供了View->controller->model的结构。
本来昨天想修改CI的源代码来编写CI_Service 类,来增加services层。但是感觉对core代码改动
很大,可能会影响CI的核心功能。
不知道有没有遇到类似的问题?
有没有更好的办法,尽量不要改动CodeIgniter.php的基础上扩展来增加Service层级?
期待大牛的帮忙~ 扩展核心 你看下面可否, 通过 $this->load->service('user_service');来调用。
也可以让所有的service集成一个common service, common service实现__get魔术方法获取CI对象的属性和方法。
也就和控制器一样方便了, 至于怎么划分service, 那就要个人功力了。
<?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 */
我也遇到这个问题~不知道楼主解决没有。。可否告知下 求助一下: 我拷贝了楼上的代码,然后再在core下面写了个My_Service,在application下面的新建service文件夹,然后其它的service 继承My_Service ,就报错: Fatal error: Class 'MY_Service' not found in 。。。。。\application\service\user_service.php on line 3,难道我需要在每个Service一开始require My_Service 么? 解决了,谢谢,
直接在My_Loader 里面 require 进去My_Service类,是个土办法,管用
页:
[1]