Codeigniter: Use of load_class

拥有回忆 提交于 2020-01-11 13:54:12

问题


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 a load_class function I can't assign to anything in the CI user guide.

1 Why do they put this into an extra function?

2 What/where loads this function files from?

Hope there are some CI guys how can answer :-)


回答1:


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.



来源:https://stackoverflow.com/questions/8771336/codeigniter-use-of-load-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!