2

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

3
  • Extend this function into common helper class like this stackoverflow.com/questions/37648935/…. Or create trait or behavior. Commented Aug 25, 2016 at 5:24
  • thanks for comment but i am not understand!! please explain how to send parameters from another action class Commented Aug 25, 2016 at 5:29
  • What do you mean send parameters? You just pass them as arguments of function. Commented Aug 25, 2016 at 5:56

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

change Yii::$app->MyComponent->MyFunction(4,2); to Yii::$app->mycomponent->MyFunction(4,2);
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.