从Yii2中的另一个控制器访问控制器

时间:2015-03-27 00:03:33

标签: php yii2

有没有办法从FirstControllerSecondController访问该功能?如果有,可以请有人给我指路。

FirstController

class FirstController extends Controller
{
    public function actionDownload($fileName)
    {
        $path = 'templates/'.$fileName;
        if(file_exists($path)){
            return Yii::$app->response->sendFile($path);
        }
    }
}


SecondController

class SecondController extends Controller
{
    public function actionView($id)
    {

        // i want to access function download() from the FirstController here

        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }
}

1 个答案:

答案 0 :(得分:0)

您可以重构代码

FirstController

use app\models\Downloader;

class FirstController extends Controller
{
    public function actionDownload($fileName)
    {
        Downloader::download($filename);
    }
}

SecondController

use app\models\Downloader;

class SecondController extends Controller
{
    public function actionView($id)
    {
        $filename = "file"; // set this as you wish

        Downloader::download($filename);

        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }
}

Downloader@app/models

namespace app\models;

class Downloader
{
    public static function download(string $filename)
    {
        $path = 'templates/'.$fileName;
        if (file_exists($path)) {
            return Yii::$app->response->sendFile($path);
        }
    }
}