如何让CI框架支持service层,CI框架service层
如何让CI框架支持service层,CI框架service层
大家知道CodeIgniter框架式MVC分层的,通常大家把业务逻辑写到Controller中,而Model只负责和数据库打交道。
但是随着业务越来越复杂,controller越来越臃肿,举一个简单的例子,比如说用户下订单,这必然会有一系列的操作:更新购物车、添加订单记录、会员添加积分等等,且下订单的过程可能在多种场景出现,如果这样的代码放controller中则很臃肿难以复用,如果放model会让持久层和业务层耦合。现在公司的项目就是,很多人将一些业务逻辑写到model中去了,model中又调其它model,也就是业务层和持久层相互耦合。这是极其不合理的,会让model难以维护,且方法难以复用。
是不是可以考虑在controller和model中加一个业务层service,由它来负责业务逻辑,封装好的调用接口可以被controller复用。
这样各层的任务就明确了:
Model(DAO):数据持久层的工作,对数据库的操作都封装在这。
Service : 业务逻辑层,负责业务模块的逻辑应用设计,controller中就可以调用service的接口实现业务逻辑处理,提高了通用的业务逻辑的复用性,设计到具体业务实现会调用Model的接口。
Controller :控制层,负责具体业务流程控制,这里调用service层,将数据返回到视图
View : 负责前端页面展示,与Controller紧密联系。
基于上面描述,实现过程:
(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
{
/**
* List of loaded sercices
*
* @var array
* @access protected
*/
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 :
复制代码 代码如下:
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 :
复制代码 代码如下:
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打交道:
复制代码 代码如下:
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');
}
}
基本实现思路就是这样的。
都是要实践的,而且要由浅入深。建议去找找一些人际开发的简单的CI功能,比如一些进度管理系统啊,社区啊之类的,多看看system下面的library和helper,了解CI基础的功能函数,再试着接触core文件夹下的核心文件,你会运用自如的。
无论CI怎么NB, 他都是PHP,php加载文件不都是包括嘛 如include,有些时候不要想的太多致无法入手 ,简单就好/。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











When using complex data structures in Java, Comparator is used to provide a flexible comparison mechanism. Specific steps include: defining the comparator class, rewriting the compare method to define the comparison logic. Create a comparator instance. Use the Collections.sort method, passing in the collection and comparator instances.

Data structures and algorithms are the basis of Java development. This article deeply explores the key data structures (such as arrays, linked lists, trees, etc.) and algorithms (such as sorting, search, graph algorithms, etc.) in Java. These structures are illustrated through practical examples, including using arrays to store scores, linked lists to manage shopping lists, stacks to implement recursion, queues to synchronize threads, and trees and hash tables for fast search and authentication. Understanding these concepts allows you to write efficient and maintainable Java code.

Reference types are a special data type in the Go language. Their values do not directly store the data itself, but the address of the stored data. In the Go language, reference types include slices, maps, channels, and pointers. A deep understanding of reference types is crucial to understanding the memory management and data transfer methods of the Go language. This article will combine specific code examples to introduce the characteristics and usage of reference types in Go language. 1. Slices Slices are one of the most commonly used reference types in the Go language.

AVL tree is a balanced binary search tree that ensures fast and efficient data operations. To achieve balance, it performs left- and right-turn operations, adjusting subtrees that violate balance. AVL trees utilize height balancing to ensure that the height of the tree is always small relative to the number of nodes, thereby achieving logarithmic time complexity (O(logn)) search operations and maintaining the efficiency of the data structure even on large data sets.

Overview of Java Collection Framework The Java collection framework is an important part of the Java programming language. It provides a series of container class libraries that can store and manage data. These container class libraries have different data structures to meet the data storage and processing needs in different scenarios. The advantage of the collection framework is that it provides a unified interface, allowing developers to operate different container class libraries in the same way, thereby reducing the difficulty of development. Data structures of the Java collection framework The Java collection framework contains a variety of data structures, each of which has its own unique characteristics and applicable scenarios. The following are several common Java collection framework data structures: 1. List: List is an ordered collection that allows elements to be repeated. Li

The hash table can be used to optimize PHP array intersection and union calculations, reducing the time complexity from O(n*m) to O(n+m). The specific steps are as follows: Use a hash table to map the elements of the first array to a Boolean value to quickly find whether the element in the second array exists and improve the efficiency of intersection calculation. Use a hash table to mark the elements of the first array as existing, and then add the elements of the second array one by one, ignoring existing elements to improve the efficiency of union calculations.

Overview of the PHPSPL Data Structure Library The PHPSPL (Standard PHP Library) data structure library contains a set of classes and interfaces for storing and manipulating various data structures. These data structures include arrays, linked lists, stacks, queues, and sets, each of which provides a specific set of methods and properties for manipulating data. Arrays In PHP, an array is an ordered collection that stores a sequence of elements. The SPL array class provides enhanced functions for native PHP arrays, including sorting, filtering, and mapping. Here is an example of using the SPL array class: useSplArrayObject;$array=newArrayObject(["foo","bar","baz"]);$array

In-depth study of the mysteries of Go language data structure requires specific code examples. As a concise and efficient programming language, Go language also shows its unique charm in processing data structures. Data structure is a basic concept in computer science, which aims to organize and manage data so that it can be accessed and manipulated more efficiently. By in-depth learning the mysteries of Go language data structure, we can better understand how data is stored and operated, thereby improving programming efficiency and code quality. 1. Array Array is one of the simplest data structures
