Welcome Guest, Not a member yet? Register   Sign In
How to load singleton library
#1

[eluser]Hallas[/eluser]
Hello,

I have created library for logging, it is singleton class but in CI2 when I try to load it - it throws error :

Fatal error: Call to private Logger::__construct() from context 'CI_Loader'

even if I pass null as instance name.

$this->load->library('Logger','',null);

Can someone help about this ?

Code:
class Logger {
    private static $_instance;
    private $_fp;
    
    private function __construct()
    {
       $this->_fp = fopen('log.txt', 'a');
    }

    public function __destruct()
    {
        fclose($this->_fp);
    }

    public function log($text)
    {
        // Log stuff...
    }


    public static function getInstance()
    {
        if (self::$_instance === null) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
}
#2

[eluser]zoopstud[/eluser]
Construct shouldn't be private.
#3

[eluser]Kamarg[/eluser]
In order to properly implement the singleton pattern, construct is almost always private. However, in PHP there is rarely any reason to actually use the singleton pattern. You might want to rethink your reasoning. More reading on why not to use singletons in PHP.
#4

[eluser]Unknown[/eluser]
try using the
Code:
class Logger {
    private static $_instance = new Logger();
    private $_fp;
    
    private function __construct()
    {
       $this->_fp = fopen('log.txt', 'a');
    }

    public function __destruct()
    {
        fclose($this->_fp);
    }

    public function log($text)
    {
        // Log stuff...
    }


    public static function getInstance()
    {
        return Logger::$_instance;
    }
}
#5

[eluser]Aken[/eluser]
Guys, the problem is that he's trying to load it through the Loader class, which will ALWAYS instantiate a new class if it does not exist. It does not look for a singleton pattern or a getInstance() method.

You'll need to either extend the Loader core file, require the file manually somewhere in your application (you can do it globally or per controller, whatever you need), or add the class to something like a config file or index.php (making it available [mostly] globally).




Theme © iAndrew 2016 - Forum software by © MyBB