使用以下代码,您可以加载控制器类并执行方法。
此代码是为笨2.1书面
首先在你的应用程序/核心目录中添加一个新的文件MY_Loader.php
。下面的代码添加到您的新创建的文件MY_Loader.php
:
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
// written by AJ [email protected]
class MY_Loader extends CI_Loader
{
protected $_my_controller_paths = array();
protected $_my_controllers = array();
public function __construct()
{
parent::__construct();
$this->_my_controller_paths = array(APPPATH);
}
public function controller($controller, $name = '', $db_conn = FALSE)
{
if (is_array($controller))
{
foreach ($controller as $babe)
{
$this->controller($babe);
}
return;
}
if ($controller == '')
{
return;
}
$path = '';
// Is the controller in a sub-folder? If so, parse out the filename and path.
if (($last_slash = strrpos($controller, '/')) !== FALSE)
{
// The path is in front of the last slash
$path = substr($controller, 0, $last_slash + 1);
// And the controller name behind it
$controller = substr($controller, $last_slash + 1);
}
if ($name == '')
{
$name = $controller;
}
if (in_array($name, $this->_my_controllers, TRUE))
{
return;
}
$CI =& get_instance();
if (isset($CI->$name))
{
show_error('The controller name you are loading is the name of a resource that is already being used: '.$name);
}
$controller = strtolower($controller);
foreach ($this->_my_controller_paths as $mod_path)
{
if (! file_exists($mod_path.'controllers/'.$path.$controller.'.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_Controller'))
{
load_class('Controller', 'core');
}
require_once($mod_path.'controllers/'.$path.$controller.'.php');
$controller = ucfirst($controller);
$CI->$name = new $controller();
$this->_my_controllers[] = $name;
return;
}
// couldn't find the controller
show_error('Unable to locate the controller you have specified: '.$controller);
}
}
现在你可以加载在你的应用程序/控制器目录中的所有控制器。 例如:
负载控制器类发票并执行功能测试()
$this->load->controller('invoice','invoice_controller');
$this->invoice_controller->test();
,或者当类内的DIR
$this->load->controller('/dir/invoice','invoice_controller');
$this->invoice_controller->test();
这只是工作相同等装载型号
看起来您正在使用控制器来制作数据。我建议你使用模型,这样你就可以独立于你所在的控制器调用模型的方法(MVC'瘦身控制器,胖模型') – 2011-05-22 22:04:44
我更喜欢讨论部件或部件 - 我很想拥有一致的模块来放置网站模板。这或多或少需要实例化控制器。 – Daniel 2011-05-22 22:53:10