Welcome Guest, Not a member yet? Register   Sign In
Getting a loaded library instance: how?
#1

[eluser]Unknown[/eluser]
I want to load a library specified in a config file as a string. Since the name of the class can change, I do to not want to hardcode it.

Code:
$authclass = $this->config->item('authenticator');
$this->load->library($authclass);
I could refer to this library statically:
Code:
$this->authenticator->foo();
But. how can I refer to this library dynamically? Something like:
Code:
$this->$authclass->foo();
Alternatively, is there a way so that:
Code:
$auth = $this->load->library($authclass);
then you'd think either this would work:
Code:
$this->$auth->foo();
or this
Code:
$auth->foo();
Thanks.
#2

[eluser]dcunited08[/eluser]
Quote:[url="http://ellislab.com/codeigniter/user-guide/libraries/loader.html"]Assigning a Library to a different object name[/url]

If the third parameter is blank, the library will usually be assigned to an object with the same name as the library. For example, if the library is named Session, it will be assigned to a variable named $this->session.

If you prefer to set your own class names you can pass its value to the third parameter:
Code:
$this->load->library('session','','my_session');

// Session class is now accessed using:
$this->my_session

Use this to load the different libraries as the same name. Make sure that these libraries are written with in interface, that way you are can guarantee that the called functions will all have the same name.
#3

[eluser]drewbee[/eluser]
optimus,

It can be achieved by assigning a variable then using that variable.

Code:
$authclass = 'authenticator';
$this->$authclass->foo();

Easy, eh? Smile
#4

[eluser]Unknown[/eluser]
I also got this working, but will give the suggestions above a try since they seem a little cleaner.

Code:
$authclass = 'LDAPAuthenticator';
$this->load->library($authclass);
$authenticator = new $authclass();
$authenticator->foo();

dcunited08, the authentication interface is defined by 'Authenticator' and there are subclasses such as LDAPAuthenticator, MySQLAuthenticator, etc.

Thanks all!
#5

[eluser]m4rw3r[/eluser]
You get two instances of the authentication object there (which may create some bugs, if the constructor eg. uses db and similar state changing things).

So you should go with either dcunited08's solution or drewbee's solution. (personally I prefer dcunited08's variant).




Theme © iAndrew 2016 - Forum software by © MyBB