簡體   English   中英

從另一個控制器調用動作並返回數據 Yii2

[英]Calling action from another controller and returning data Yii2

我有控制器,我需要從另一個控制器訪問操作並返回數據:

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
}

我該怎么做?

如果您需要重用另一個控制器的操作,您可以這樣做:

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

但我不推薦它。 我建議您將邏輯移至另一個組件,以便兩個控制器都可以使用它。

重用另一個控制器動作的最簡單方法是使用這個:

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

雖然我不推薦它。 最好在模型中使用您想要的信息創建一個靜態函數,然后在需要的地方調用它。

你必須在模型中做這樣的工作,MVC 模式中的控制器不應該做邏輯。 您的控制器應該只調用模型方法並返回結果。

在您的情況下,您想要的模型應該擴展 yii\\base\\Model 並且應該像這樣使用

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

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

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM