Home  >  Article  >  Backend Development  >  How to make the CI framework support the service layer, CI framework service layer_PHP tutorial

How to make the CI framework support the service layer, CI framework service layer_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:15:45906browse

How to make CI framework support service layer, CI framework service layer

Everyone knows that the CodeIgniter framework is layered in MVC. Usually people write business logic into the Controller, and the Model is only responsible for dealing with the database.

But as the business becomes more and more complex, the controller becomes more and more bloated. To give a simple example, for example, if a user places an order, there will inevitably be a series of operations: updating the shopping cart, adding order records, members adding points, etc. etc., and the process of placing orders may occur in various scenarios. If such code is placed in the controller, it will be bloated and difficult to reuse. If placed in the model, the persistence layer and the business layer will be coupled. The current company's project is that many people write some business logic into the model, and the model adjusts other models, that is, the business layer and the persistence layer are coupled to each other. This is extremely unreasonable and will make the model difficult to maintain and the methods difficult to reuse.

Is it possible to consider adding a business layer service to the controller and model, which will be responsible for the business logic, and the encapsulated calling interface can be reused by the controller.

In this way, the tasks of each layer are clear:
Model (DAO): The work of the data persistence layer and the operations on the database are all encapsulated here.
Service: The business logic layer is responsible for the logical application design of the business module. The service interface can be called in the controller to implement business logic processing, which improves the reusability of general business logic. When designing the specific business implementation, the Model interface will be called.
Controller: Control layer, responsible for specific business process control. Here the service layer is called to return data to the view
View: Responsible for front-end page display and closely connected with Controller.

Based on the above description, the implementation process:
(1) Let CI be able to load service. The service directory is placed under application. Because the CI system does not have service, create a new extension MY_Service.php

under application/core.

Copy code The code is as follows:

class MY_Service
{
Public function __construct()
{
Log_message('debug', "Service Class Initialized");
}
Function __get($key)
{
          $CI = & get_instance();
          return $CI->$key;
}
}

(2) Extend the CI_Loader implementation, load the service, and create a new MY_Loader.php file under application/core:

Copy code The code is as follows:

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) Simple example implementation:
Call service in the controller:

Copy code The code is as follows:

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));
}
}

Calling model in service:

Copy code The code is as follows:

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;
}
}

In model you only deal with db:

Copy code The code is as follows:

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');
}
}

The basic implementation idea is this.

How to learn CI framework

It all requires practice, and it must proceed from the shallower to the deeper. It is recommended to look for some simple CI functions developed by people, such as some progress management systems, communities, etc. Look at the libraries and helpers under the system to understand the basic functions of CI, and then try to access the core folder. You will be able to use the core files below.

How to load custom data structures in the CI framework

No matter how NB CI is, it is all PHP. PHP loading files all include, for example, include. Sometimes, don’t think too much and fail to start. Just keep it simple/.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/902774.htmlTechArticleHow to make the CI framework support the service layer. Everyone knows that the CI framework service layer is layered in the CodeIgniter framework MVC. Usually everyone Write the business logic into the Controller, and the Model is only responsible for communicating with the database...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn