Call function in another controller in Yii

I created 2 controllers in a Yii application: FirstController.php and SecondController.php in the default controller path.

FirstController.php:

<?php class FirstController extends Controller { public static function returnFunc() { return 'OK'; } } 

SecondController.php:

 <?php class SecondController extends Controller { public function exampleFunc() { $var = First::returnFunc(); } } 

When I try to execute exampleFunc() in SecondController, Yii throws an error:

 YiiBase::include(FirstController.php) [<a href='function.YiiBase-include'>function.YiiBase-include</a>]: failed to open stream: No such file or directory 

Calling FirstController::returnFunc() does not work in the same way.

I am new to OOP and Yii. What is the problem?

+7
oop php yii
source share
3 answers

I solved this problem. Autoloader does not load controllers.

This was in config/main.php :

 'import' => array( 'application.models.*', 'application.components.*', ), 

Everyone works with this:

 'import' => array( 'application.models.*', 'application.components.*', 'application.controllers.*', ), 
+11
source share
 class ServiceController extends Controller { public function actionIndex() { Yii::import('application.controllers.back.ConsolidateController'); // ConsolidateController is another controller in back controller folder echo ConsolidateController::test(); // test is action in ConsolidateController class ServiceController extends Controller { public function actionIndex() { Yii::import('application.controllers.back.CservicesController'); $obj =new CservicesController(); // preparing object echo $obj->test(); exit; // calling method of CservicesController 
+4
source share

When you create a Yii project, each of your controllers extends the Controller class, and this class extends the built-in CController of the Yii class.

This is good because Controller is a class in your application (you can find it in the components folder).

If you want the method to be available for both of your controllers, put this method in the Controller class and, as they both extend it. They will both gain access. Just be sure to declare it public or secure.

+2
source share

All Articles