我有两个控制器SubmitPerformanceController和PrintReportController。
在PrintReportController中,我有一个叫做getPrintReport的方法。
如何在submitperformanceccontroller中访问此方法?
我有两个控制器SubmitPerformanceController和PrintReportController。
在PrintReportController中,我有一个叫做getPrintReport的方法。
如何在submitperformanceccontroller中访问此方法?
当前回答
namespace App\Http\Controllers;
//call the controller you want to use its methods
use App\Http\Controllers\AdminController;
use Illuminate\Http\Request;
use App\Http\Requests;
class MealController extends Controller
{
public function try_call( AdminController $admin){
return $admin->index();
}
}
其他回答
你不应该。这是反模式。如果你在一个控制器中有一个方法,你需要在另一个控制器中访问,那么这是你需要重构的标志。
考虑将方法重构到一个服务类中,然后可以在多个控制器中实例化该服务类。所以如果你需要为多个模型提供打印报告,你可以这样做:
class ExampleController extends Controller
{
public function printReport()
{
$report = new PrintReport($itemToReportOn);
return $report->render();
}
}
在我看来最优雅的方法是:
app(YourController::class)->yourControllerMethod()
你可以通过实例化它并调用doAction来访问控制器:(put use Illuminate\Support\Facades\App;在控制器类声明之前)
$controller = App::make('\App\Http\Controllers\YouControllerName');
$data = $controller->callAction('controller_method', $parameters);
还要注意,这样做将不会执行该控制器上声明的任何中间件。
如果您在另一个控制器中需要该方法,这意味着您需要抽象它并使其可重用。将该实现移动到服务类(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
}
}
对需要该实现的其他控制器执行相同的操作。从其他控制器中获取控制器方法是一种代码气味。
\App::call('App\Http\Controllers\MyController@getFoo')