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

Daniyal
  • 184
  • 5
  • 24
  • Extend this function into common helper class like this http://stackoverflow.com/questions/37648935/in-yii2-framework-better-place-to-define-common-function-which-is-accessible-ev/37649292#37649292. Or create trait or behavior. – SiZE Aug 25 '16 at 05:24
  • thanks for comment but i am not understand!! please explain how to send parameters from another action class – Daniyal Aug 25 '16 at 05:29
  • What do you mean send parameters? You just pass them as arguments of function. – xReprisal Aug 25 '16 at 05:56

2 Answers2

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);
Muhammad Shahzad
  • 9,340
  • 21
  • 86
  • 130
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.

Nico Savini
  • 458
  • 3
  • 10