我有两个控制器SubmitPerformanceController和PrintReportController。

在PrintReportController中,我有一个叫做getPrintReport的方法。

如何在submitperformanceccontroller中访问此方法?


当前回答

你可以通过实例化它并调用doAction来访问控制器:(put use Illuminate\Support\Facades\App;在控制器类声明之前)

$controller = App::make('\App\Http\Controllers\YouControllerName');
$data = $controller->callAction('controller_method', $parameters);

还要注意,这样做将不会执行该控制器上声明的任何中间件。

其他回答

如果您在另一个控制器中需要该方法,这意味着您需要抽象它并使其可重用。将该实现移动到服务类(ReportingService或类似的东西)并将其注入到控制器中。

例子:

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

对需要该实现的其他控制器执行相同的操作。从其他控制器中获取控制器方法是一种代码气味。

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

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

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

你可以扩展PrintReportController,这样SubmitPerformanceController将继承这个方法

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

但这也会从PrintReportController继承所有其他方法。

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

trait PrintReport {

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

告诉你的控制器使用这个特性:

class PrintReportController extends Controller {
     use PrintReport;
}

class SubmitPerformanceController extends Controller {
     use PrintReport;
}

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

你可以在这里阅读更多关于特质的内容。

这种方法也适用于相同层次的Controller文件:

$printReport = new PrintReportController;

$prinReport->getPrintReport();

你可以在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();

    }

}

不建议从另一个控制器调用一个控制器,但是如果出于任何原因你必须这样做,你可以这样做:

Laravel 5兼容方法

return \App::call('bla\bla\ControllerName@functionName');

注意:这不会更新页面的URL。

最好是调用Route,让它调用控制器。

return \Redirect::route('route-name-here');