Using Helper Functions Outside Controller |
[eluser]CmdrMoozy[/eluser]
Suppose I have a helper called "foobar" defined like this: Code: <?php if(!defined("BASEPATH")) exit("No direct script access allowed"); I add this helper to the list of automatically loaded helpers in config/autoload.php, and now in a controller, I want to do this: Code: <?php The problem is that this fails, saying getFoobar() isn't defined (I assume this is because the loading of helpers and other things occurs when I call parent::__construct() in a controller). How can I access helper functions outside of controllers?
[eluser]CroNiX[/eluser]
Try Code: class Foobar extends CI_Controller
[eluser]CroNiX[/eluser]
Here's a good tutorial on what you can do with base controllers. http://philsturgeon.co.uk/blog/2010/02/C...ing-it-DRY I highly recommend reading it as it really makes things simpler.
[eluser]CmdrMoozy[/eluser]
That is the obvious solution, but in this case I'm not sure it works. The issue I'm having is that, in my particular case, getFoobar() returns a path to a PHP file I want to include, and doing require_once() inside of a class doesn't really do what one expects (due to scoping).
[eluser]CroNiX[/eluser]
Why don't you have the helper instantiate the class and return the object instead of that way?
[eluser]CmdrMoozy[/eluser]
The object needs some data to be instantiated, which the helper doesn't have reasonable access to. As for making it a library, my understanding is that libraries typically are single-use - i.e., there will only ever be a single instance of a library, whereas my object lets me manage data, and I might have several instances of it in use at once.
[eluser]CroNiX[/eluser]
The helper can access anything that CI has loaded or has access to. Code: $CI =& get_instance(); But with a library, you could just autoload it, bring CI into it (as above) and use whatever needed in the construct to get your stuff. Then that library will be available to all of your controllers/views/other libraries/etc since its autoloaded. Code: class some_class { |
Welcome Guest, Not a member yet? Register Sign In |