Reputation: 4431
I want to call a function in another controller from the controller.
class FirstController extends Controller {
public function test1() { return 'OK'; }
}
class SecondController extends Controller {
public function callTest1() { First::test1(); }
}
--> server error
Help me resolve it.
Upvotes: 5
Views: 25278
Reputation: 634
Instead of using createController which creates an instance based on a route, when calling via code, it's probably best to use createControllerByID.
$first = Yii::$app->createControllerByID('first');
$first->test1();
Make sure test1 is public function
Upvotes: 1
Reputation: 132
This worked for me,
for PatientsController and method printPublicReport() with $params = $patientId, $appId, $testIds
list($patient) = Yii::$app->createController('patients/print-public-report', $postDataAry);
$patient->printPublicReport($patientId, $appId, $testIds);
Upvotes: 0
Reputation: 11
In Yii2 basic application following component will be use to call action
Yii::$app->runAction('controllername/create', $params);
Upvotes: 1
Reputation: 59
The word 'Controller' should not be used when calling createController() and you should take [0] element of the result, before calling functions
$process = Yii::app()->createController('First'); //create instance of FirstController
$process=$process[0];
$process->test1(); //call function
Upvotes: 1
Reputation: 915
If method test1
in your FirstController
is not using $this
you can simply make it static
. Instead of:
public function test1() { return 'OK'; }
sign it as:
public static function test1() { return 'OK'; }
Then you can call it from everywhere:
FirstController::test1();
It all depends on your needs...
Upvotes: 0
Reputation: 1
You cannot call directly your function: first create instance of controller, then call function:
$process = Yii::app()->createController('FirstController'); //create instance of controller
$process->test1(); //call function
Upvotes: 0
Reputation: 437336
You cannot call that method directly because it's not static
, so you 'd have to create an instance of FirstController
first. When you want to do that, use CWebApplication::createController
:
// supply appropriate route in place of 'first/index'
list($first) = Yii::app()->createController('first/index');
$first->test1();
However, there shouldn't be a need to call methods from another controller; this is a bad code smell. Perhaps it would be more appropriate to refactor your code and pull it out of the controller (maybe into a model).
Upvotes: 9