Welcome Guest, Not a member yet? Register   Sign In
[Solved] Codeigniter: Load Library in a Core Class
#7

(This post was last modified: 11-01-2016, 08:55 AM by dave friend.)

Here's the same answer I posted in response to your stackoverflow question.

I'd be interested in this community's thoughts on my answer.

*********

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

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.

application/libraries/Logger.php

PHP Code:
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);
 
   }



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

PHP Code:
$this->load->library('logger'); 

A usage example might be something like this

PHP Code:
$this->logger->write_log('error'"This is FUBAR"); 

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

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

could be done this way instead

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

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.
Reply


Messages In This Thread
RE: Codeigniter: Load Library in a Core Class - by dave friend - 11-01-2016, 07:46 AM



Theme © iAndrew 2016 - Forum software by © MyBB