Laravel 5:控制器内部通信和实例化


Laravel 5: Controller Inter-Communication and Instantiation

在过去,我使用了一个类似Objective-C的视图控制器方案的专有框架。

基本上,我能够在一个控制器中实例化另一个控制器,并向其传递一些值,如乘积数组,然后将对控制器的引用注入到我的视图中,并通过发出:$controllerReference->render(); 随时渲染它

这在很多情况下都很有用,例如,如果我有一个负责呈现目录的控制器,我只需向它传递一个包含我想看到的所有项目的数组,它就会自行进行分页和显示项目。。。

示例:

At''UI''Homepage''Controller.php(负责主页的控制器):

// Instantiate a ProductDisplay Controller
$controllRef = new 'UI'ProductDisplay'Controller();
$controllRef->setProducts( ... ); // Inject the product array
// Load the current view for this controller and pass it a reference for the ProductDisplay controller
$this->loadSelfView(["controllRef" => $controllRef]);

At''UI''Homepage''View.php(之前加载的视图):

// some html of the view
$controllRef->render(); // Render the ProductDisplay view here!
// some other html

该如何在Laravel中实现此功能?从我读到的内容来看,拉拉威尔试图避免这种行为,为什么?解决办法是什么?

谢谢。

以下是我将如何做到这一点,只有当被调用的控制器方法返回类似return view('home');的View对象时,它才能工作):

// Get the controller class from the IOC container
$myController= 'App::make(MyController::class); 
// Execute the controller method (which return a View object)
$view = $myController->myControllerMethod($someParams); 
// Return the View html content
$html = $view->render(); 

您可以使用由所有其他控制器扩展的Controller.php类,在其中创建一个通用方法:

  1. 获取控制器实例
  2. 使用x参数调用正确的方法
  3. 如果是视图类,则返回呈现的内容,或者抛出异常(例如)

在Laravel的最新版本中,可以使用Blade的@inject指令。它的主要目的似乎是注入服务,但我成功地注入了控制器操作。

这里有一个关于你必须做的事情的片段:

@inject('productController', 'App'Http'Controllers'ProductController')
{!! $productController->index() !!}

请记住:由于您直接调用controller方法,而不是通过路由器,因此必须传递所有必需的params。如果该操作需要一个请求实例,您可以这样称呼它:

{!! $productController->index(request()) !!}

被调用的操作返回的视图可能包含HTML代码。将方法调用封装在{!!!!}中非常重要。使用常规的{{ }}标记将导致HTML代码被模板引擎转义。