Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter : calling a method of one controller from other

Tags:

codeigniter

I have two controllers a and b.

I would like to call a method of controller a from a method of controller b.

Could anyone help explain how I can achieve this?

like image 875
koool Avatar asked Jun 27 '11 23:06

koool


People also ask

Can we call one controller from another controller in codeigniter?

Codeigniter (and MVC in general) aren't designed to work this way. Controllers don't call other controllers. If you find yourself needing to do that it's likely an indicator that your app architecture needs some refactoring.

How can we call one controller function from another controller in PHP?

Show activity on this post. Create new Helper (e.g PermissionHelper. php ) then move the funtion to it and call it where you want using : PermissionHelper::permission();


2 Answers

This is not supported behavior of the MVC System. If you want to execute an action of another controller you just redirect the user to the page you want (i.e. the controller function that consumes the url).

If you want common functionality, you should build a library to be used in the two different controllers.

I can only assume you want to build up your site a bit modular. (I.e. re-use the output of one controller method in other controller methods.) There's some plugins / extensions for CI that help you build like that. However, the simplest way is to use a library to build up common "controls" (i.e. load the model, render the view into a string). Then you can return that string and pass it along to the other controller's view.

You can load into a string by adding true at the end of the view call:

$string_view = $this->load->view('someview', array('data'=>'stuff'), true); 
like image 103
Aren Avatar answered Sep 27 '22 21:09

Aren


test.php Controller File :

Class Test {  function demo() {   echo "Hello";  } } 

test1.php Controller File :

Class Test1 {  function demo2() {   require('test.php');   $test = new Test();   $test->demo();  } } 
like image 32
Rkk Avatar answered Sep 27 '22 23:09

Rkk