Laravel 5中另一个控制器的Access Controller方法 [英] Access Controller method from another controller in Laravel 5

查看:62
本文介绍了Laravel 5中另一个控制器的Access Controller方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个控制器SubmitPerformanceControllerPrintReportController.

PrintReportController中,我有一个名为getPrintReport的方法.

In PrintReportController I have a method called getPrintReport.

如何在SubmitPerformanceController中访问此方法?

推荐答案

您可以这样访问控制器方法:

You can access your controller method like this:

app('App\Http\Controllers\PrintReportController')->getPrintReport();

这可以工作,但是在代码组织方面很糟糕(请记住为您的PrintReportController使用正确的名称空间)

This will work, but it's bad in terms of code organisation (remember to use the right namespace for your PrintReportController)

您可以扩展PrintReportController,以便SubmitPerformanceController将继承该方法

You can extend the PrintReportController so SubmitPerformanceController will inherit that method

class SubmitPerformanceController extends PrintReportController {
     // ....
}

但是,这还将继承PrintReportController中的所有其他方法.

But this will also inherit all other methods from PrintReportController.

最好的方法是创建一个trait(例如在app/Traits中),在其中实现逻辑并告诉您的控制器使用它:

The best approach will be to create a trait (e.g. in app/Traits), implement the logic there and tell your controllers to use it:

trait PrintReport {

    public function getPrintReport() {
        // .....
    }
}

告诉您的控制器使用此特征:

Tell your controllers to use this trait:

class PrintReportController extends Controller {
     use PrintReport;
}

class SubmitPerformanceController extends Controller {
     use PrintReport;
}

两个解决方案都使SubmitPerformanceController具有getPrintReport方法,因此您可以在控制器内使用$this->getPrintReport();或直接将其作为路由(如果您将其映射到routes.php中)调用

Both solutions make SubmitPerformanceController to have getPrintReport method so you can call it with $this->getPrintReport(); from within the controller or directly as a route (if you mapped it in the routes.php)

您可以在此处中了解更多有关特征的信息.

You can read more about traits here.

这篇关于Laravel 5中另一个控制器的Access Controller方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆