CI3中添加自己的library,并且使用CI的特性

CI可以很方便的扩展自己的类,但是当我们扩展自己类的时候,很多时候会调用CI中的其他特性,那么需要使用get_instance来达到我们想要的效果

1、在application\controllers\User.php中,调用了自己写的一个类theme

<?php
	defined('BASEPATH') OR exit('No direct script access allowed');
	class User extends BaseController{
		public function __construct(){
			parent::__construct();
			$this->load->library('theme');
		}
		
		/**
		*list
		**/
		public function lists(){
			$users = [
				[
					'name'=>'ken',
					'age'=>'23',
				],
				[
					'name'=>'lkicy',
					'age'=>'32',
				],
			];
			
			//$this->load->view('user/list',['users'=>$users]);
			$this->theme->show('user/list',['users'=>$users]);
		}

2、在application\libraries新建Theme.php文件

<?php 
	defined('BASEPATH') OR exit('No direct script access allowed');
	/**
	*主题系统
	*/
class Theme{
	
	protected $CI;
	public function __construct(){
		$this->CI =& get_instance();
	}
	
	public function show($template,$data){
		$this->CI->load->view('header');
		$this->CI->load->view($template,$data);
		$this->CI->load->view('footer');
	}
}


由于要使用到CI中的view视图,所以需要执行

$this->CI =& get_instance();

当然,不一定要放到__construct中执行,放到里面执行是为了全局调用方便。


你可能感兴趣的:(CI3中添加自己的library,并且使用CI的特性)