PHP Trait |一个实例说明 PHP trait 的使用

因为需要在 Laravel 中的一个 controller 中调用,另一个 controller 的方法,所以在 Google 搜索到下面这篇文章。

该文章所说,遇到这种情况,最适合的处理方式就是使用 trait。

原文:
http://stackoverflow.com/questions/30365169/access-controller-method-from-another-controller-in-laravel-5

#1方案:抽象声明一个 service class,引入使用

If you need that method in another controller, that means you need to abstract it and make it reusable. Move that implementation into a service class (ReportingService or something similar) and inject it into your controllers.

Example:

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
  }
}

Do the same for the other controllers where you need that implementation. Reaching for controller methods from other controllers is a code smell.

#2方案:使用 php trait

You can access your contoller method like this:

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

This will work, but this is bad in terms of code organisation (remember to put the right namespace for your PrintReportContoller if it is different).

You can extend the PrintReportContoller so your SubmitPerformanceController will inherit this method class

SubmitPerformanceController extends PrintReportContoller { ....}

But this will also inherit all other methods from PrintReportController.
The best approach will be to create a trait, implement the logic there and tell your controllers to use it:

trait PrintReport { public function getPrintReport() { ..... }}

Tell you controllers they use this trait:

class PrintReportContoller extends Controller { 
    use PrintReport;
}

class SubmitPerformanceController extends Controller { 
    use PrintReport;
}

Both solutions make SubmitPerformanceController
to have getPrintReport function, 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)

你可能感兴趣的:(PHP Trait |一个实例说明 PHP trait 的使用)