2015-03-27 4 views
0

Есть ли способ получить доступ к функции от FirstController до SecondController? если есть, может понравиться, кто-то покажет мне дорогу.

FirstController:
Контроллер доступа от другого контроллера в Yii 2

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), 
     ]); 
    } 
} 

ответ

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); 
     } 
    } 
} 
+1

Спасибо. это так полезно –

Смежные вопросы