Welcome Guest, Not a member yet? Register   Sign In
Call a private controller method from within another controller
#1

[eluser]wbremen[/eluser]
Hey there,

In a controller I have a privat method (function _name()) which is heavely depending on the other methods in that specific controller and also on the model of that controller - know I need access to that function in all my other controllers, is that possible, maybe with a workaround?

I was thinking of something like this:

$this->get_controller_function->controller_name->_method_name();

Thanks
#2

[eluser]CroNiX[/eluser]
A few choices.
1) HVMC. This will let you create modules (mini applications) which can be called from multiple controllers, but might be overkill if you just need it for something small.
2) Library. Create a library class that is doing what you need. Then call the library from the controllers that need it.
Code:
class New_class
{
    public CI;

    public function __construct()
    {
        parent::__construct();
        $this->CI =& get_instance();
    }

    public function something()
    {
        $this->CI->load->model('some_model');
        return $this->CI->some_model->get_data();
    }
}

...in some controller...

Code:
$this->load->library('new_class');
$class_data = $this->new_class->something();
...in some other controller...
Code:
$this->load->library('new_class');
$class_data = $this->new_class->something();
#3

[eluser]wbremen[/eluser]
Okay thanks...

Was looking for a way without having to rewrite the code but it seems like I will for shifting those functions to a library.

New question: Can you call Models from within a Library?
#4

[eluser]CroNiX[/eluser]
Sure, just like my code above does. Once you have access to the CI superglobal/instance, you can do anything you can normally do with CI.

Its not that hard to make a library from existing code. Mostly just copy/paste. Except everywhere that you use "$this" it would now be "$this->CI" assuming you instantiated it like I did above.
#5

[eluser]wbremen[/eluser]
Thanks alot




Theme © iAndrew 2016 - Forum software by © MyBB