我有两个控制器SubmitPerformanceController和PrintReportController。
在PrintReportController中,我有一个叫做getPrintReport的方法。
如何在submitperformanceccontroller中访问此方法?
我有两个控制器SubmitPerformanceController和PrintReportController。
在PrintReportController中,我有一个叫做getPrintReport的方法。
如何在submitperformanceccontroller中访问此方法?
当前回答
\App::call('App\Http\Controllers\MyController@getFoo')
其他回答
如果您在另一个控制器中需要该方法,这意味着您需要抽象它并使其可重用。将该实现移动到服务类(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(YourController::class)->yourControllerMethod()
你可以在PrintReportController中使用一个静态方法,然后像这样从SubmitPerformanceController调用它;
namespace App\Http\Controllers;
class PrintReportController extends Controller
{
public static function getPrintReport()
{
return "Printing report";
}
}
namespace App\Http\Controllers;
use App\Http\Controllers\PrintReportController;
class SubmitPerformanceController extends Controller
{
public function index()
{
echo PrintReportController::getPrintReport();
}
}
这种方法也适用于相同层次的Controller文件:
$printReport = new PrintReportController;
$prinReport->getPrintReport();
晚回复,但我一直在寻找这个时间。这现在可以用一种非常简单的方式实现。
如果没有参数
return redirect()->action('HomeController@index');
与参数
return redirect()->action('UserController@profile', ['id' => 1]);
文档:https://laravel.com/docs/5.6/responses # redirecting-controller-actions
在5.0中,它需要完整的路径,现在它简单多了。