我有两个控制器SubmitPerformanceController和PrintReportController。
在PrintReportController中,我有一个叫做getPrintReport的方法。
如何在submitperformanceccontroller中访问此方法?
我有两个控制器SubmitPerformanceController和PrintReportController。
在PrintReportController中,我有一个叫做getPrintReport的方法。
如何在submitperformanceccontroller中访问此方法?
当前回答
你不应该。这是反模式。如果你在一个控制器中有一个方法,你需要在另一个控制器中访问,那么这是你需要重构的标志。
考虑将方法重构到一个服务类中,然后可以在多个控制器中实例化该服务类。所以如果你需要为多个模型提供打印报告,你可以这样做:
class ExampleController extends Controller
{
public function printReport()
{
$report = new PrintReport($itemToReportOn);
return $report->render();
}
}
其他回答
\App::call('App\Http\Controllers\MyController@getFoo')
这里trait完全模拟了laravel路由器的运行控制器(包括对中间件和依赖注入的支持)。仅在5.4版本中测试
<?php
namespace App\Traits;
use Illuminate\Pipeline\Pipeline;
use Illuminate\Routing\ControllerDispatcher;
use Illuminate\Routing\MiddlewareNameResolver;
use Illuminate\Routing\SortedMiddleware;
trait RunsAnotherController
{
public function runController($controller, $method = 'index')
{
$middleware = $this->gatherControllerMiddleware($controller, $method);
$middleware = $this->sortMiddleware($middleware);
return $response = (new Pipeline(app()))
->send(request())
->through($middleware)
->then(function ($request) use ($controller, $method) {
return app('router')->prepareResponse(
$request, (new ControllerDispatcher(app()))->dispatch(
app('router')->current(), $controller, $method
)
);
});
}
protected function gatherControllerMiddleware($controller, $method)
{
return collect($this->controllerMidlleware($controller, $method))->map(function ($name) {
return (array)MiddlewareNameResolver::resolve($name, app('router')->getMiddleware(), app('router')->getMiddlewareGroups());
})->flatten();
}
protected function controllerMidlleware($controller, $method)
{
return ControllerDispatcher::getMiddleware(
$controller, $method
);
}
protected function sortMiddleware($middleware)
{
return (new SortedMiddleware(app('router')->middlewarePriority, $middleware))->all();
}
}
然后将它添加到类中并运行控制器。注意,依赖注入将与当前路由一起分配。
class CustomController extends Controller {
use RunsAnotherController;
public function someAction()
{
$controller = app()->make('App\Http\Controllers\AnotherController');
return $this->runController($controller, 'doSomething');
}
}
//In Controller A <br >
public static function function1(){
}
//In Controller B, View or anywhere <br>
A::function1();
你可以通过实例化它并调用doAction来访问控制器:(put use Illuminate\Support\Facades\App;在控制器类声明之前)
$controller = App::make('\App\Http\Controllers\YouControllerName');
$data = $controller->callAction('controller_method', $parameters);
还要注意,这样做将不会执行该控制器上声明的任何中间件。
晚回复,但我一直在寻找这个时间。这现在可以用一种非常简单的方式实现。
如果没有参数
return redirect()->action('HomeController@index');
与参数
return redirect()->action('UserController@profile', ['id' => 1]);
文档:https://laravel.com/docs/5.6/responses # redirecting-controller-actions
在5.0中,它需要完整的路径,现在它简单多了。