CI3使用加载类

加载器类

加载器,顾名思义,是用于加载元素的,加载的元素可以是库(类),视图文件 , 驱动器 ,辅助函数 , 模型 或其他你自己的文件。

 

应用程序包

目录结构

 

/application/third_party/foo_bar
//文件夹可选
config/
helpers/
language/
libraries/
models/
views/

 

 

读取视图、配置文件

  

public function index()
    {        
        $this->load->add_package_path(APPPATH . 'third_party/foo_bar', FALSE);            //加载附属程序
        $this->load->config('zhangsan');                        //加载附属程序的配置文件
        $this->config->set_item('zhangsan', '李四');
        $res = $this->config->item('zhangsan');

        $this->load->view('hh');            //加载附属程序的视图文件
    }

 

读取辅助函数

1、创建辅助函数

 

<?php

function you()
{$ci = &get_instance();
    $hello = $ci->load->database('hello', true);
    $res = $hello->get('admin')->result_array();
    p($res);
}

 

2、加载并调用辅助函数

function lisi()
    {
        $this->load->add_package_path(APPPATH . 'third_party/foo_bar');
        $this->load->helper('hp');
        you();
    }

 

调用数据库

1、config/database.php中添加数据库连接

$db['hello'] = array(
    'dsn'    => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => 'root',
    'database' => 'temp',
    'dbdriver' => 'mysqli',
    'dbprefix' => 'cms_',
    'pconnect' => TRUE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

2、helper辅助函数中操作数据库

<?php

function you()
{
    echo 444;
    $ci = &get_instance();
    $ci->load->add_package_path(APPPATH . 'third_party/foo_bar');
    $hello = $ci->load->database('hello', true);    //加载数据库组名称
    $res = $hello->get('admin')->result_array();
    p($res);
}

 

使用驱动器:

创建驱动器drv:

 

function qudong()
    {
        $this->load->add_package_path(APPPATH . 'third_party/foo_bar');
        $this->load->driver('drv');      //必须在add_package_path下面调用
        $this->drv->file->save();
    }

 

遇到的bug,第二个参数不起作用

$this->load->add_package_path(APPPATH.'my_app', FALSE);

查找原因发现,原来是system/core/Loader.php,函数里面,返回的数组,导致始终返回的是加载类的视图路径
  $this->_ci_view_paths = array($path . 'views/' => $view_cascade) + $this->_ci_view_paths;  

 

修改代码为就好:
$this->_ci_view_paths = $view_cascade ? array($path . 'views/' => $view_cascade) : $this->_ci_view_paths;

 

 

 

posted @ 2024-07-25 11:18  哆啦阿梦  阅读(1)  评论(0编辑  收藏  举报