4
votes

I have controller where I need to access an action from another controller and return data:

rest/controllers/AController

switch (@$_GET['barcodeType']) 
{
    case '1D':
    {  
            //do action Request1 from BController and return data from 
            this controller
    }
    break;

    case '2D':
    {
            //do action Request2 from BController and return data from 
            this controller
    }
    break;

    default:
    return  ['Wrong barcodeType'];
    break; 
}

soap/controllers/BController

public actionRequest1{
    //do something and return data to AController
}

public actionRequest2{
    //do something and return data to AController
}

How can I do this?

3
when you say do an action are you referring any simple function inside that controller or anactionFunction - Muhammad Omer Aslam
Prepare one action with param $barcode and then call function depending on passed barcodeType. Don't call different controller actions. Greetings for Human-Device. - Yupik

3 Answers

10
votes

You can do this, if you need to reuse another controller's action:

$result = Yii::$app->runAction('b/request1', ['param1' => 'value1', /* ... */]);

But I don't recommend it. I suggest you to move the logic to another component, so both controllers can use it.

2
votes

The easiest way to resuse another controllers action is to use this:

return $this->redirect(['controller_name/index']); 

Though i dont recommend it. It would be better to create a static function with the information you want in the model and then call it where you need it.

1
votes

You must do work like that in a model, a controller in the MVC pattern isn't supposed to do logic. Your controllers should just call models method and return the result.

In your case the model you want should extends yii\base\Model and should be used like

switch (@$_GET['barcodeType']) 
{
    case '1D':
    {  
            return Barcode1D::doWork();
    }
    break;

    case '2D':
    {
            return Barcode2D::doWork();
    }
    break;

    default:
    return  ['Wrong barcodeType'];
    break; 
}

and

public actionRequest1{
    return Barcode1D::doWork();
}

public actionRequest2{
    return Barcode2D::doWork();
}