正在为你努力加载中........

点滴记录 分享
16
2014-5
首页 >> CodeIgniter >> CI 重写model方法,可以传递初始化参数

CI 重写model方法,可以传递初始化参数

看了CI的model方法 默认没有传递初始化参数

public function model($model, $name = '', $db_conn = FALSE)
在core下面新建MY_Loader.php

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * MY_Model Class
 * @author      speakphp.com QQ:821200318
 */
class MY_Loader extends CI_Loader
{

	/**
	 * Model Loader  扩展CI的model
	 *
	 * This function lets users load and instantiate models.
	 *
	 * @param	string	the name of the class
	 * @param	string	name for the model
	 * @param	bool	database connection
	 * @param	string	array('type'=>'real_data') 调用哪个数据库, 此处还可以传递别的参数,增加即可
	 * @return	void
	 */
	public function model($model, $name = '', $db_conn = FALSE , $type_str = array('type'=>'real_data') )
	{
		if (is_array($model))
		{
			foreach ($model as $babe)
			{
				$this->model($babe);
			}
			return;
		}

		if ($model == '')
		{
			return;
		}

		$path = '';

		// Is the model in a sub-folder? If so, parse out the filename and path.
		if (($last_slash = strrpos($model, '/')) !== FALSE)
		{
			// The path is in front of the last slash
			$path = substr($model, 0, $last_slash + 1);

			// And the model name behind it
			$model = substr($model, $last_slash + 1);
		}

		if ($name == '')
		{
			$name = $model;
		}

		if (in_array($name, $this->_ci_models, TRUE))
		{
			return;
		}

		$CI =& get_instance();
		if (isset($CI->$name))
		{
			show_error('The model name you are loading is the name of a resource that is already being used: '.$name);
		}

		$model = strtolower($model);

		foreach ($this->_ci_model_paths as $mod_path)
		{
			if ( ! file_exists($mod_path.'models/'.$path.$model.'.php'))
			{
				continue;
			}

			if ($db_conn !== FALSE AND ! class_exists('CI_DB'))
			{
				if ($db_conn === TRUE)
				{
					$db_conn = '';
				}

				$CI->load->database($db_conn, FALSE, TRUE);
			}

			if ( ! class_exists('CI_Model'))
			{
				load_class('Model', 'core');
			}

			require_once($mod_path.'models/'.$path.$model.'.php');

			$model = ucfirst($model);

			$CI->$name = new $model($type_str);

			$this->_ci_models[] = $name;
			return;
		}

		// couldn't find the model
		show_error('Unable to locate the model you have specified: '.$model);
	}
	
}
控制器这样调用:

$this->load->model('M_common','',false , array('type'=>'real_data'));
其中第四个参数是传递的默认初始值

看下 M_common.php文件

function M_common($params = array() ){
		$type = '' ;
		$type =( isset($params['type']) && $params['type'] )? $params['type'] : 'real_data' ;
		parent::__construct();
		$this->db = $this->load->database($type,true);
	}


作者:一根烟的寂寞 分类:CodeIgniter
浏览:3856 评论:0

发表评论: