且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Codeigniter:核心类中的加载库

更新时间:2023-11-19 17:22:16

扩展 CI_Log $如果您需要访问其他库,则c $ c>不起作用。原因是在创建 $ CI 之前创建 CI_Log 很久,因此对于& 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.