CodeIgniter Forums
Call a private controller method from within another controller - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Call a private controller method from within another controller (/showthread.php?tid=37651)



Call a private controller method from within another controller - El Forum - 01-16-2011

[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


Call a private controller method from within another controller - El Forum - 01-16-2011

[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();



Call a private controller method from within another controller - El Forum - 01-16-2011

[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?


Call a private controller method from within another controller - El Forum - 01-16-2011

[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.


Call a private controller method from within another controller - El Forum - 01-16-2011

[eluser]wbremen[/eluser]
Thanks alot