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

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

问题描述

我有两个控制器 SubmitPerformanceControllerPrintReportController.

I have two controllers SubmitPerformanceController and PrintReportController.

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

In PrintReportController I have a method called getPrintReport.

如何在SubmitPerformanceController中访问这个方法?

How to access this method in SubmitPerformanceController?

推荐答案

你可以像这样访问你的控制器方法:

You can access your controller method like this:

app('AppHttpControllersPrintReportController')->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 中另一个控制器的访问控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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