Problem:
In Laravel, you have two controllers, SubmitPerformanceController and PrintReportController. You wish to invoke a method, getPrintReport, from PrintReportController within SubmitPerformanceController. How can you achieve this?
Answer:
There are several approaches to access controller methods across controllers in Laravel 5:
Method 1: Using the app() Helper
<code class="php">app('App\Http\Controllers\PrintReportController')->getPrintReport();</code>
This approach retrieves the PrintReportController class instance and executes its getPrintReport method directly. While it works, it's not recommended due to organization concerns.
Method 2: Inheritance
<code class="php">class SubmitPerformanceController extends PrintReportController { // ... }</code>
By extending PrintReportController, SubmitPerformanceController inherits all its methods, including getPrintReport. However, this approach also inherits all other methods, which may not be necessary.
Method 3: Traits
Creating a trait (e.g., app/Traits) is considered the最佳做法:`
<code class="php">trait PrintReport { public function getPrintReport() { // ... } } class PrintReportController extends Controller { use PrintReport; } class SubmitPerformanceController extends Controller { use PrintReport; }</code>
By using traits, SubmitPerformanceController can access the getPrintReport method as a controller method (e.g., $this->getPrintReport()). Both SubmitPerformanceController and PrintReportController can access getPrintReport this way.
The above is the detailed content of How to Access Controller Methods in Laravel 5: A Guide to Methods and Best Practices. For more information, please follow other related articles on the PHP Chinese website!