Reputation: 184
I am new to YII use yii2 basic.actually i want to know How to call an common function from action of the same controller. Suppose I am in action A for send mail. I need to call send mail function B with three parameters its reurns some value. My controller name is Customer Controller. How will I perform this. Please say me a solution. Thanks
Upvotes: 2
Views: 2611
Reputation: 9652
For yii2, First Make a folder named "components" in your project root folder.
Then write your custom component inside components folder .i.e MyComponent.php or anything.
namespace app\components;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
class MyComponent extends Component
{
public function MyFunction($param1,$param2){
return $param1+$param2; // (:)
}
}
Now add your component inside the config file.
'components' => [
'mycomponent' => [
'class' => 'app\components\MyComponent',
],
]
Access in your app:
Yii::$app->mycomponent->MyFunction(4,2);
Upvotes: 3
Reputation: 487
If it's shared only within the controller, you could just create a function inside it. The components in Yii2 should be use for Application purposes (to be shared between more than one controller).
private function myFunction(a, b){
return a+b;
}
And then call it from anywher in your controller
public function actionSomeAction(){
if(myFunction(1,2)>4){...}
}
Also the ideas of the component is to have more functionality that just a function, for example to have all users' behavior.
Upvotes: 0