Welcome Guest, Not a member yet? Register   Sign In
Accessing CI Router object from a custom library class
#1

[eluser]BBBThunda[/eluser]
I am writing a custom Library which needs the ability to get the name of the current controller and insert/update a database record with the info.

I need this to be reusable and not dependent on the URI to be modeled a certain way, so I don't think using the URI helper will work here. Doing it this way would also cause problems when the controller is determined by route configurations, etc.

I am pretty sure using the Router (CI_Router?) object is the way to go since CI stores the name of the controller in the object. It seems CI automatically stores this info in the Router::class variable.

I've seen the following suggestions for accessing it:

Code:
$this->router->class;

Code:
$this->router->fetch_class();

Neither of these work since I'm coding this within a library class which, although called by the controller class, is separate from the controller. Therefore these suggestions result in error messages like this:

Code:
Message: Undefined property: Mylibrary::$router

How can I access the Router object from my library? Do I need to somehow grab the reference from the Router object and pass it into my constructor? (hopefully not)

Or is there a better way to handle this?
#2

[eluser]theprodigy[/eluser]
According to the user guide,
Quote:First, assign the CodeIgniter object to a variable:
$CI =& get_instance();

Once you've assigned the object to a variable, you'll use that variable instead of $this:
$CI =& get_instance();

$CI->load->helper('url');
$CI->load->library('session');
$CI->config->item('base_url');
etc.

So, in your case, you would use:
Code:
$CI =& get_instance();
$CI->router->class;
#3

[eluser]BBBThunda[/eluser]
Thanks for the quick reply, theprodigy! That looks like it might be the answer I was looking for, assuming "get_instance()" is a globally defined function. I will try this out and reply back with my results.
#4

[eluser]theprodigy[/eluser]
Quote:I will try this out and reply back with my results.
Should I assume by your silence that this worked for you?
Please reply so that others who view this thread will know whether or not it worked, and if it will work for them.
#5

[eluser]BBBThunda[/eluser]
Sorry for the delay. I did a simple test and it worked. Thanks very much for the help.

I'm planning to do some more thorough testing, but if I run into any issues I'll start another topic.

You can consider this one resolved.




Theme © iAndrew 2016 - Forum software by © MyBB