我有两个控制器SubmitPerformanceController和PrintReportController。
在PrintReportController中,我有一个叫做getPrintReport的方法。
如何在submitperformanceccontroller中访问此方法?
我有两个控制器SubmitPerformanceController和PrintReportController。
在PrintReportController中,我有一个叫做getPrintReport的方法。
如何在submitperformanceccontroller中访问此方法?
当前回答
尝试在SubmitPerformanceController中创建一个新的PrintReportController对象,并直接调用getPrintReport方法。
例如,假设我在SubmitPerformanceController中有一个名为“Test”的函数,然后我可以这样做:
public function test() {
$prc = new PrintReportController();
$prc->getPrintReport();
}
其他回答
//In Controller A <br >
public static function function1(){
}
//In Controller B, View or anywhere <br>
A::function1();
在我看来最优雅的方法是:
app(YourController::class)->yourControllerMethod()
晚回复,但我一直在寻找这个时间。这现在可以用一种非常简单的方式实现。
如果没有参数
return redirect()->action('HomeController@index');
与参数
return redirect()->action('UserController@profile', ['id' => 1]);
文档:https://laravel.com/docs/5.6/responses # redirecting-controller-actions
在5.0中,它需要完整的路径,现在它简单多了。
你可以在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();
}
}
你可以通过实例化它并调用doAction来访问控制器:(put use Illuminate\Support\Facades\App;在控制器类声明之前)
$controller = App::make('\App\Http\Controllers\YouControllerName');
$data = $controller->callAction('controller_method', $parameters);
还要注意,这样做将不会执行该控制器上声明的任何中间件。