创建service层 将业务逻辑及判断 放到service层
1.创建service层
(1)让CI能够加载service,service目录放在application下,因为CI系统没有service,则在application/core下新建扩展MY_Service.php
class MY_Service
{
public function __construct()
{
log_message('debug', "Service Class Initialized");
}
function __get($key)
{
$CI = & get_instance();
return $CI->$key;
}
}
2.扩展CI_Loader实现,加载service,在application/core下新建 MY_Loader.php文件:
class MY_Loader extends CI_Loader
{
protected $_ci_services = array();
/**
* List of paths to load sercices from
*
* @var array
* @access protected
*/
protected $_ci_service_paths = array();
/**
* Constructor
*
* Set the path to the Service files
*/
public function __construct()
{
parent::__construct();
$this->_ci_service_paths = array(APPPATH);
}
/**
* Service Loader
*
* This function lets users load and instantiate classes.
* It is designed to be called from a user's app controllers.
*
* @param string the name of the class
* @param mixed the optional parameters
* @param string an optional object name
* @return void
*/
public function service($service = '', $params = NULL, $object_name = NULL)
{
if(is_array($service))
{
foreach($service as $class)
{
$this->service($class, $params);
}
return;
}
if($service == '' or isset($this->_ci_services[$service])) {
return FALSE;
}
if(! is_null($params) && ! is_array($params)) {
$params = NULL;
}
$subdir = '';
// Is the service in a sub-folder? If so, parse out the filename and path.
if (($last_slash = strrpos($service, '/')) !== FALSE)
{
// The path is in front of the last slash
$subdir = substr($service, 0, $last_slash + 1);
// And the service name behind it
$service = substr($service, $last_slash + 1);
}
foreach($this->_ci_service_paths as $path)
{
$filepath = $path .'service/'.$subdir.$service.'.php';
if ( ! file_exists($filepath))
{
continue;
}
include_once($filepath);
$service = strtolower($service);
if (empty($object_name))
{
$object_name = $service;
}
$service = ucfirst($service);
$CI = &get_instance();
if($params !== NULL)
{
$CI->$object_name = new $service($params);
}
else
{
$CI->$object_name = new $service();
}
$this->_ci_services[] = $object_name;
return;
}
}
}
3简单例子实现:控制器中调用service :
<?php
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->service('user_service');
}
public function login()
{
$name = 'phpddt.com';
$psw = 'password';
print_r($this->user_service->login($name, $psw));
}
}
-
service中调用model :
<?php class User_service extends MY_Service { public function __construct() { parent::__construct(); $this->load->model('user_model'); } public function login($name, $password) { $user = $this->user_model->get_user_by_where($name, $password); return $user; } }
-
model中你只跟db打交道:
<?php class User_model extends CI_Model { public function __construct() { parent::__construct(); } public function get_user_by_where($name, $password) { //$this->db return array('id' => 1, 'name' => 'mckee'); } }
参考网址https://www.cnblogs.com/hellowzd/p/4674666.html