Laravel 4:路由到localhost/controller/action [英] Laravel 4 : Route to localhost/controller/action
问题描述
我或多或少是Laravel 4的新手.我以前从未使用过路由,但是通常我习惯的是url/controller/action,然后是我的后端路由.我已经阅读了几次有关路由和控制器的文档,并通读了一些教程,因此,我试图找出如何在不为每个控制器和动作编写路由的情况下使它起作用.
I'm more or less new to Laravel 4. I've never used routes before but normally what I'm used to is url/controller/action and then the backend routing for me. I've read the documentation for routes and controllers a few times as well as read through some tutorials and so, I'm trying to figure out how to get this to work without writing a route for every controller and action.
我尝试了
Route::get('{controller}/{action}', function($controller, $action = 'index'){
return $controller."@".$action;
});
现在,我知道这是错误的,因为它不起作用,但是我想念的是什么?在大多数教程和资料中,我看到了一条或多或少的控制器和动作之类的路线:
Now then, I know this is wrong since it doesn't work, but what am I missing? On most tutorials and stuff I'm seeing an route for more or less every controller and action like:
Route::get('/controller/action' , 'ControllerName@Action');
这对我来说似乎很愚蠢,就像在浪费时间.
Which seems silly and like a waste of time to me.
反正有实现我想要的东西吗?
Is there anyway to achieve what I want?
推荐答案
如果您正在寻找更自动化的路由,这将是Laravel 4的方式:
If you are looking for a more automated routing, this would be the Laravel 4 way:
路线:
Route::controller('users', 'UsersController');
控制器(在本例中为UsersController.php):
Controller (in this case UsersController.php):
public function getIndex()
{
// routed from GET request to /users
}
public function getProfile()
{
// routed from GET request to /users/profile
}
public function postProfile()
{
// routed from POST request to /users/profile
}
public function getPosts($id)
{
// routed from GET request to: /users/posts/42
}
正如Shift Exchange所述,以冗长的方式进行操作有一些好处.除了他链接的出色文章之外,您还可以为每个路线创建一个名称,例如:
As The Shift Exchange mentioned, there are some benefits to doing it the verbose way. In addition to the excellent article he linked, you can create a name for each route, for example:
Route::get("users", array(
"as"=>"dashboard",
"uses"=>"UsersController@getIndex"
));
然后在应用程序中创建url时,使用帮助程序生成链接到命名路由:
Then when creating urls in your application, use a helper to generate a link to a named route:
$url = URL::route('dashboard');
然后通过对控制器/操作的更改来证明链接的未来.
Links are then future proofed from changes to controllers/actions.
您还可以直接生成指向仍可用于自动路由的操作的链接.
You can also generate links directly to actions which would still work with automatic routing.
$url = URL::action('UsersController@getIndex');
这篇关于Laravel 4:路由到localhost/controller/action的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!