Codeigniter:核心类中的加载库 [英] Codeigniter: Load Library in a Core Class

查看:52
本文介绍了Codeigniter:核心类中的加载库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用几个函数扩展 /system/core/Log.php 库。如果发生错误,则一个函数应通过自定义函数 sendMail()发送邮件,该函数是 Custom_library.php

I want to extend the /system/core/Log.php library with a couple of functions. One function should send a mail in case of an error via the custom function sendMail() which is part of the Custom_library.php.

因此,我创建了文件 /application/core/MY_Log.php

class MY_Log extends CI_Log {
  public function __construct()
  {
    parent::__construct();
  }

  public function write_log($level, $msg)
  {
    $result = parent::write_log($level, $msg);

    return $result;
  }
}

问题:我无法加载 Custom_library.php 。这些方法都不起作用:

The problem: I'm not able to load the Custom_library.php. None of these approaches worked:

//approach 1    
$this->load->library('Custom_library');

//approach 2  
$CI =& get_instance();
$CI->load->library('Custom_library');

方法2的错误消息:

Fatal error: Uncaught Error: Class 'CI_Controller' not found in /home/gp/public_html/system/core/CodeIgniter.php:366 Stack trace: #0 /home/gp/public_html/application/core/MY_Log.php(13): get_instance() #1 /home/gp/public_html/system/core/Common.php(478): MY_Log->write_log('error', 'Severity: error...') #2 /home/gp/public_html/system/core/Exceptions.php(105): log_message('error', 'Severity: error...') #3 /home/gp/public_html/system/core/Common.php(662): CI_Exceptions->log_exception('error', 'Exception: Clas...', '/home/gp/public...', 366) #4 [internal function]: _exception_handler(Object(Error)) #5 {main} thrown in /home/gp/public_html/system/core/CodeIgniter.php on line 366

问题:是否可以在核心类中加载和利用库?

The question: Is it possible to load and utilize a Library in a Core Class?

我尝试了通过函数& load_class

function &load_class($class, $directory = 'libraries', $param = NULL)
    {
        static $_classes = array();

        // Does the class exist? If so, we're done...
        if (isset($_classes[$class]))
        {
            return $_classes[$class];
        }

        $name = FALSE;

        // Look for the class first in the local application/libraries folder
        // then in the native system/libraries folder
        foreach (array(APPPATH, BASEPATH) as $path)
        {
            if (file_exists($path.$directory.'/'.$class.'.php'))
            {
                $name = 'CI_'.$class;

                if (class_exists($name, FALSE) === FALSE)
                {
                    require_once($path.$directory.'/'.$class.'.php');
                }

                break;
            }
        }

        // Is the request a class extension? If so we load it too
        if (file_exists(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php'))
        {
            $name = config_item('subclass_prefix').$class;

            if (class_exists($name, FALSE) === FALSE)
            {
                require_once(APPPATH.$directory.'/'.$name.'.php');
            }
        }

        // Did we find the class?
        if ($name === FALSE)
        {
            // Note: We use exit() rather than show_error() in order to avoid a
            // self-referencing loop with the Exceptions class
            set_status_header(503);
            echo 'Unable to locate the specified class: '.$class.'.php';
            exit(5); // EXIT_UNK_CLASS
        }

        // Keep track of what we just loaded
        is_loaded($class);

        $_classes[$class] = isset($param)
            ? new $name($param)
            : new $name();
        return $_classes[$class];
    }

如果我运行函数 $ CI =& load_class('Custom_library'); 会找到正确的文件,但会查找带有前缀 CI_的Class。并因此引发并显示错误消息:

If I run the function $CI =& load_class('Custom_library'); it finds the right file but than is looking for the Class with a prefix "CI_" and thus throws and error message:

Fatal error: Uncaught Error: Class 'CI_Custom_library' not found in /home/gp/public_html/system/core/Common.php:196 Stack trace: #0 /home/gp/public_html/application/core/MY_Log.php(14): load_class('Custom_library') #1 /home/gp/public_html/system/core/Common.php(478): MY_Log->write_log('error', 'Severity: error...') #2 /home/gp/public_html/system/core/Exceptions.php(105): log_message('error', 'Severity: error...') #3 /home/gp/public_html/system/core/Common.php(662): CI_Exceptions->log_exception('error', 'Exception: Clas...', '/home/gp/public...', 196) #4 [internal function]: _exception_handler(Object(Error)) #5 {main} thrown in /home/gp/public_html/system/core/Common.php on line 196


推荐答案

扩展 CI_Log 不起作用。原因是在创建 $ CI 之前创建 CI_Log 很久,因此对于<$ c $没有可用的实例 c>& get_instance()返回。

Extending CI_Log is not going to work if you need to access other libraries. The reason is CI_Log is created long before $CI is created so no "instance" is available for &get_instance() to return.

$ this->加载不起作用,因为 $ this 不是控制器( $ this $ CI 指向同一对象)和类 load ('CI_Loader')尚未创建。

$this->load doesn't work because $this is not a controller ($this and $CI point to the same object) and the class load ('CI_Loader') hasn't been created yet either.

解决这个问题的方法可能不止一种。在我看来,最不容易破解的方法是使您的记录器类使用 CI_Log 而不是扩展

There might be more than one way around this. Seems to me the least hacked way is to make your logger class utilize CI_Log instead of extend it.

应用程序/库/Logger.php

class Logger
{
    protected $CI;

    public function __construct()
    {
        $this->CI = & get_instance();
        $this->CI->load->library('custom_library');
    }

    public function write_log($level, $msg)
    {
        //do stuff with "custom_library"
         $this->CI->custom_library->some_function();

        //use the built-in logging mechanism, a.k.a. CI_Log
        return log_message($level, $msg);
    }

}

您的记录器将需要与其他任何库一样加载到Controller中。

Your `logger' will need to be loaded in a Controller the same as any other library.

$this->load->library('logger');

使用示例可能是这样的

$this->logger->write_log('error', "This is FUBAR");

在您呼叫 $ this-> load-> library时('logger'); log 类已创建,并且是 $ CI (又名 $ this )。因此,此行

By the time you call $this->load->library('logger'); the log class has been created and is part of $CI (a.k.a. $this). So this line

    //use the built-in logging mechanism, a.k.a. CI_Log
    return log_message($level, $msg);

可以用这种方式完成

    //use the built-in logging mechanism, a.k.a. CI_Log
    return $this->CI->log->write_log($level, $msg);

由于所有 log_message 确实还是调用 log-> write_log 。我没有看到任何问题,而不是使用 log_message

That would be marginally more efficient since all log_message does is call log->write_log anyway. I don't see any problem doing this instead of using log_message.

有趣的问题,我学到了很多看着它。谢谢。

Interesting question and I learned a bunch by looking into it. Thanks.

这篇关于Codeigniter:核心类中的加载库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆