3 回答

TA貢獻1851條經驗 獲得超4個贊
您可以這樣訪問控制器方法:
app('App\Http\Controllers\PrintReportController')->getPrintReport();
這可以工作,但是在代碼組織方面很不好(請記住為您使用正確的名稱空間PrintReportController)
您可以擴展,PrintReportController以便SubmitPerformanceController將繼承該方法
class SubmitPerformanceController extends PrintReportController {
// ....
}
但這也會繼承的所有其他方法PrintReportController。
最好的方法是創建一個trait(例如app/Traits),在其中實現邏輯并告訴您的控制器使用它:
trait PrintReport {
public function getPrintReport() {
// .....
}
}
告訴您的控制器使用此特征:
class PrintReportController extends Controller {
use PrintReport;
}
class SubmitPerformanceController extends Controller {
use PrintReport;
}
兩種解決方案都SubmitPerformanceController具有getPrintReport方法,因此您可以$this->getPrintReport();在控制器內使用或直接將其作為路徑調用(如果您在中將其映射routes.php)
您可以在這里閱讀更多有關特征的信息。

TA貢獻1796條經驗 獲得超4個贊
如果您需要在另一個控制器中使用該方法,則意味著您需要對其進行抽象并使其可重用。將該實現移到服務類(ReportingService或類似的類)中,并將其注入到控制器中。
例:
class ReportingService
{
public function getPrintReport()
{
// your implementation here.
}
}
// don't forget to import ReportingService at the top (use Path\To\Class)
class SubmitPerformanceController extends Controller
{
protected $reportingService;
public function __construct(ReportingService $reportingService)
{
$this->reportingService = $reportingService;
}
public function reports()
{
// call the method
$this->reportingService->getPrintReport();
// rest of the code here
}
}
對需要該實現的其他控制器執行相同的操作。從其他控制器獲取控制器方法是一種代碼味道。

TA貢獻1900條經驗 獲得超5個贊
不建議從另一個控制器調用一個控制器,但是,如果由于某種原因必須這樣做,則可以執行以下操作:
Laravel 5兼容方法
return \App::call('bla\bla\ControllerName@functionName');
注意:這不會更新頁面的URL。
最好改為調用Route并讓它調用控制器。
return \Redirect::route('route-name-here');
添加回答
舉報