php ci get instance,PHP CI框架中如何实现类库的自动加载及别名逻辑处理

本文深入探讨了PHP CI框架中类库自动加载的实现过程,从app/controllers/Index.php中的代码出发,逐步解析了加载流程,涉及$autoload['libraries']配置、Loader类的initialize方法、_ci_autoloader函数以及_library方法。文章详细解释了如何处理别名,如$autoload['libraries'] = array('Yredis','validation'=>'sn'),并展示了加载过程中涉及的关键文件和方法,帮助读者理解CI框架内部的自动加载机制。" 111779482,10418880,Mybatis快速入门:配置文件详解,"['Mybatis', '持久层框架', 'ORM']
摘要由CSDN通过智能技术生成

缘由

app/controllers/Index.php中有如下代码

public function disable(){

$this->yredis->set('name','tb');

var_dump($this->yredis->get('name'));

$this->load->view('welcome_message');

}

发现这个yredis没有load,怎么来的?翻翻手册,有自动加载配置

在app/config/autoload.php中配置,部分内容如下

| -------------------------------------------------------------------

| Auto-load Libraries

| -------------------------------------------------------------------

| These are the classes located in system/libraries/ or your

| application/libraries/ directory, with the addition of the

| 'database' library, which is somewhat of a special case.

|

| Prototype:

|

| $autoload['libraries'] = array('database', 'email', 'session');

|

| You can also supply an alternative library name to be assigned

| in the controller:

|

| $autoload['libraries'] = array('user_agent' => 'ua');

*/

$autoload['libraries'] = array('Yredis','validation'=>'sn');

追踪一下

那么他这个自动加载是在代码内如何实现的呢?肯定从头$CI大对象来看。

在system/core/Controller.php中,有如下两句

$this->load =& load_class('Loader', 'core');

$this->load->initialize();

通过common.php中定义的load_class方法,加载了loader类。不得不说ci的核心基本都在这里了。(这个load还是个未定义的属性么...?)

我们去看system/core/Loader.php中的initialize方法,不过load的时候肯定是先加载__construct方法

public function __construct()

{

// (ob机制,不要乱配~)

$this->_ci_ob_level = ob_get_level();

$this->_ci_classes =& is_loaded();

log_message('info', 'Loader Class Initialized');

}

再回来看当前文件的initialize方法:

public function initialize()

{

$this->_ci_autoloader();

}

再去看_ci_autoloader...

protected function _ci_autoloader()

{

if (file_exists(APPPATH.'config/autoload.php'))

{

include(APPPATH.'config/autoload.php');

}

if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/autoload.php'))

{

include(APPPATH.'config/'.ENVIRONMENT.'/autoload.php');

}

if ( ! isset($autoload))

{

return;

}

// Autoload packages

if (isset($autoload['packages']))

{

foreach ($autoload['packages'] as $package_path)

{

$this->add_package_path($package_path);

}

}

// Load any custom config file

if (count($autoload['config']) > 0)

{

foreach ($autoload['config'] as $val)

{

$this->config($val);

}

}

// Autoload helpers and languages

foreach (array('helper', 'languag

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值