正在从应用程序文件夹下的其他文件夹加载Codeigniter库


Loading Codeigniter library from a different folder under application folder

嗨,我遇到问题

假设我在CodeIgniter 中有一个文件夹结构

application/
    controllers/
    models/
    views/
    gmail_library/

现在我已经写了一个控制器

class invite_friends extends CI_Controller {
    function __construct() {
        parent::__construct();
        $this->load->gmail_library('Config'); // this line is giving me error
        session_start();
    }
}

我怎么能把这个东西设置成这样?

首先,请注意CodeIgniter不使用__call()重载来实现动态方法。因此,没有办法让这样的gmail_library()方法发挥作用。

常规方法

来自用户指南:

你的库类应该放在你的application/libraries文件夹,因为这是CodeIgniter的查找位置当它们被初始化时。

如果使用CI Loader类加载库或帮助程序,则应遵循CI的约定。

应用程序/库/Myclass.php

$this->load->library('myclass');
$this->myclass->my_method();

使用相对路径

1)您将库文件放在主libraries文件夹中的子目录中:

application/libraries/gmail/Gmail_config.php
我重命名了您的Config.php文件名,以防止与CI config核心类发生冲突

$this->load->library('gmail/gmail_config');

2)还可以在Loader::library()方法中使用相对路径library文件夹外部加载库文件,如下所示:

文件的路径是相对的。因此,您可以使用../在路径中进入一个UP级别
再次:我重命名了您的Config.php文件名,以防止与CI config核心类发生冲突

$this->load->library('../gmail_library/Gmail_config');

我知道这是一个老问题,但我在寻找一种从应用程序文件夹外部使用类(库)的方法时遇到了这个问题,我喜欢将其保留在"CI方式"中。我最终扩展了CI_Loader类:

我基本上复制了_ci_load_class函数,并添加了一个绝对路径

<? if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Loader extends CI_Loader {
    protected $absPath = '/home/xxxxx/[any-path-you-like]/common/';
    /**
     * Load class
     *
     * This function loads the requested class.
     *
     * @param   string  the item that is being loaded
     * @param   mixed   any additional parameters
     * @param   string  an optional object name
     * @return  void
     */
    public function commonLibrary($class, $params = NULL, $object_name = NULL)
    {
        // Get the class name, and while we're at it trim any slashes.
        // The directory path can be included as part of the class name,
        // but we don't want a leading slash
        $class = str_replace('.php', '', trim($class, '/'));
        // Was the path included with the class name?
        // We look for a slash to determine this
        $subdir = '';
        if (($last_slash = strrpos($class, '/')) !== FALSE)
        {
            // Extract the path
            $subdir = substr($class, 0, $last_slash + 1);
            // Get the filename from the path
            $class = substr($class, $last_slash + 1);
        }
        // We'll test for both lowercase and capitalized versions of the file name
        foreach (array(ucfirst($class), strtolower($class)) as $class)
        {
            $subclass = $this->absPath.'libraries/'.$subdir.config_item('subclass_prefix').$class.'.php';
            // Is this a class extension request?
            if (file_exists($subclass))
            {
                $baseclass = BASEPATH.'libraries/'.ucfirst($class).'.php';
                if ( ! file_exists($baseclass))
                {
                    log_message('error', "Unable to load the requested class: ".$class);
                    show_error("Unable to load the requested class: ".$class);
                }
                // Safety:  Was the class already loaded by a previous call?
                if (in_array($subclass, $this->_ci_loaded_files))
                {
                    // Before we deem this to be a duplicate request, let's see
                    // if a custom object name is being supplied.  If so, we'll
                    // return a new instance of the object
                    if ( ! is_null($object_name))
                    {
                        $CI =& get_instance();
                        if ( ! isset($CI->$object_name))
                        {
                            return $this->_ci_init_class($class, config_item('subclass_prefix'), $params, $object_name);
                        }
                    }
                    $is_duplicate = TRUE;
                    log_message('debug', $class." class already loaded. Second attempt ignored.");
                    return;
                }
                include_once($baseclass);
                include_once($subclass);
                $this->_ci_loaded_files[] = $subclass;
                return $this->_ci_init_class($class, config_item('subclass_prefix'), $params, $object_name);
            }
            // Lets search for the requested library file and load it.
            $is_duplicate = FALSE;
            foreach ($this->_ci_library_paths as $path)
            {
                $filepath = $this->absPath.'libraries/'.$subdir.$class.'.php';
                // Does the file exist?  No?  Bummer...
                if ( ! file_exists($filepath))
                {
                    continue;
                }
                // Safety:  Was the class already loaded by a previous call?
                if (in_array($filepath, $this->_ci_loaded_files))
                {
                    // Before we deem this to be a duplicate request, let's see
                    // if a custom object name is being supplied.  If so, we'll
                    // return a new instance of the object
                    if ( ! is_null($object_name))
                    {
                        $CI =& get_instance();
                        if ( ! isset($CI->$object_name))
                        {
                            return $this->_ci_init_class($class, '', $params, $object_name);
                        }
                    }
                    $is_duplicate = TRUE;
                    log_message('debug', $class." class already loaded. Second attempt ignored.");
                    return;
                }
                include_once($filepath);
                $this->_ci_loaded_files[] = $filepath;
                return $this->_ci_init_class($class, '', $params, $object_name);
            }
        } // END FOREACH
        // One last attempt.  Maybe the library is in a subdirectory, but it wasn't specified?
        if ($subdir == '')
        {
            $path = strtolower($class).'/'.$class;
            return $this->_ci_load_class($path, $params);
        }
        // If we got this far we were unable to find the requested class.
        // We do not issue errors if the load call failed due to a duplicate request
        if ($is_duplicate == FALSE)
        {
            log_message('error', "Unable to load the requested class: ".$class);
            show_error("Unable to load the requested class: ".$class);
        }
    }
}

将文件MY_Loader.php放在application/core文件夹中,并使用加载您的库

$this->load->commonLibrary('optional_subfolders/classname', 'classname');
$this->classname->awesome_method();
相关文章: