(Laravel)如何在 1 条路线中使用 2 个控制器?
如何在 1 条路线中使用 2 个控制器?
How can I use 2 controllers in 1 route?
这里的目标是创建多个页面,每个页面都有 1 个职业(例如:会计师),然后将它们链接到提供会计课程的学校.
The goal here is to create multiple pages with 1 career each (e.g: Accountants) then link them to a school providing an Accounting course.
示例页面包括:
1. 会计师职业信息(我在这里使用职业"控制器)
2. 提供会计课程的学校(我在这里使用单独的学校"控制器).
An example page would consist of:
1. Accountants career information (I'm using a "career" controller here)
2. Schools providing Accounting courses (I'm using a separate "schools" controller here).
Route::get('/accountants-career', 'CareerController@accountants');
Route::get('/accountants-career', 'SchoolsController@kaplan');
使用上面的代码将覆盖控制器中的 1 个.
Using the code above will overwrite 1 of the controllers.
有没有办法解决这个问题?
Is there a solution to solve this?
推荐答案
你不能那样做,因为这不是一件好事,而且 Laravel 不会让你有相同的路线来点击两个不同的控制器动作, 除非您使用不同的 HTTP 方法(POST、GET...).Controller 是一个 HTTP 请求处理程序,而不是一个服务类,所以你可能需要稍微改变你的设计,这是一种方法:
You cannot do that, because this is not a good thing to do and by that Laravel don't let you have the same route to hit two different controllers actions, unless you are using different HTTP methods (POST, GET...). A Controller is a HTTP request handler and not a service class, so you probably will have to change your design a little, this is one way of going with this:
如果您要在一页中显示所有数据,请创建一个路由器:
If you will show all data in one page, create one single router:
Route::get('/career', 'CareerController@index');
创建一个瘦控制器,仅用于获取信息并传递给您的视图:
Create a skinny controller, only to get the information and pass to your view:
use View;
class CareerController extends Controller {
private $repository;
public function __construct(DataRepository $repository)
{
$this->repository = $repository;
}
public function index(DataRepository $repository)
{
return View::make('career.index')->with('data', $this-repository->getData());
}
}
并创建一个DataRepository类,负责知道在需要那种数据的情况下该怎么做:
And create a DataRepository class, responsible for knowing what to do in the case of need that kind of data:
class DataRepository {
public getData()
{
$data = array();
$data['accountant'] = Accountant::all();
$data['schools'] = School::all();
return $data;
}
}
请注意,此存储库会自动注入到您的控制器中,Laravel 会为您完成.
Note that this repository is being automatically inject in your controller, Laravel does that for you.
相关文章