Welcome Guest, Not a member yet? Register   Sign In
Library as singleton
#1

[eluser]manix[/eluser]
I've created a custom library using singleton pattern. Why by this way? because I need to be able to call my functions without $this-> reference, for example, I could execute the code below:

Code:
function foo() { MyLibrary::instance()->foo(); }

then I could call my functions in controllers like this:
Code:
function foo();

instance of
Code:
$this->mylibrary->foo();

I am in trouble because CodeIgniter try to instanciate my library when the best way to do (in my case) is "read" the static instance.
#2

[eluser]CroNiX[/eluser]
Then just use an include and don't use CI's load() method for that case. Just because you are using a framework doesn't mean you can't still use regular php when needed.

Code:
include_once(APPPATH . 'libraries/your_library.php';
$library = new Your_library();
$library->do_something();
#3

[eluser]manix[/eluser]
Thanks so much!
So, in order to use an unique instance in my application,
do I need to include my library in the index.php?
could I use CI object by this way in my library?
#4

[eluser]Unknown[/eluser]
Hi,

try the $CI =& get_instance() to get the codeigniter object.
#5

[eluser]manix[/eluser]
Hey, thank you so much.

I found the aswer few days ago. I have inclucde my library at core/Codeigniter.php file.. That's all Smile
#6

[eluser]CroNiX[/eluser]
I wouldn't alter core files like that. You will have a much harder time when upgrading as the upgrades can overwrite your changes, so you'll have to find all of your changes and reimplement them.

In your case, it would be MUCH better to include your library in the index.php instead of altering the core.
#7

[eluser]manix[/eluser]
Cronix, I forgot that! Yep, include it at index.php also works fine Big Grin

Thank you so much




Theme © iAndrew 2016 - Forum software by © MyBB