Laravel 4:路由到 localhost/controller/action [英] Laravel 4 : Route to localhost/controller/action

查看:16
本文介绍了Laravel 4:路由到 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
}

正如 The 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆