Codeigniter: Use of load_class

前端 未结 1 1561
死守一世寂寞
死守一世寂寞 2021-01-26 08:20

I am writing my own logging class to save data in a DB. As I looked how CI is doing I noticed there is a log_message() function which handles the logging. There is

相关标签:
1条回答
  • 2021-01-26 09:03

    Short answer: You can write your own log class to override the default CI class:

    <?php
    // this file is /application/libraries/MY_Log.php
    class MY_Log extends CI_Log {
        public function write_log($level = 'error', $msg, $php_error = FALSE)
        {
            // Put your own logging function in here.
            // If you want it to still log to a file as usual, use this:
            parent::write_log($level, $msg, $php_error);
        }
    }
    

    Long answer:

    The load_class() function is basically a singleton loader. If the class has already been loaded, return a previous instance; otherwise, load it and create the singleton. It is very important in a framework like CI. You have to know that every time you call, say, a database function, it is applying it to the same object, not instantiating a new one (that would get really messy). All CI libraries function this way by default.

    An important note: they changed how this functions significantly in version 2.0. Previously, it would only load from the /libraries folder, but now, it will load from /core or wherever you specify when calling the function.

    Here's the process for loading, say, the Log class (from your example):

    $_log =& load_class('Log');
    $_log->write_log($level, $message, $php_error);
    

    This runs the following checks, in sequence:

    1. If the Log class already exists, we're done. Return the singleton.
    2. If not, first check the /system/libraries folder for a "Log.php" file
    3. If no file existed for step #2, now check /application/libraries for a "MY_Log.php" file (or whatever your subclass prefix is set to in your configuration)
    4. If it loaded the default CI class (from the /system folder), but you DO have an extended class under /application, load that class too.
    5. Return a new instance of the class (YOURS if it exists; otherwise, it's the CI_* class)

    I've actually never needed to use the load_class() function, as it allows extension fairly seamlessly. However, it's good to know how it works.

    So, to override a class, first find where the original resides (usually /system/libraries or /system/core). Put your extending file in the corresponding /application folder (this is important! If it's under /system/core, the extension MUST be under /application/core). Prefix both the filename and the class name with MY_ (or whatever you set in your configuration), and have it extend the CI_ base class.

    0 讨论(0)
提交回复
热议问题