6

我或多或少是 Laravel 4 的新手。我以前从未使用过路由,但通常我习惯的是 url/controller/action,然后是我的后端路由。我已经阅读了几次路由和控制器的文档,并通读了一些教程,因此,我试图弄清楚如何在不为每个控制器和动作编写路由的情况下使其工作。

我尝试了类似的东西

Route::get('{controller}/{action}', function($controller, $action = 'index'){
    return $controller."@".$action;
});

现在,我知道这是错误的,因为它不起作用,但我错过了什么?在大多数教程和东西上,我或多或少地看到了每个控制器和动作的路线,例如:

Route::get('/controller/action' , 'ControllerName@Action');

这对我来说似乎很愚蠢,而且是在浪费时间。

反正有没有达到我想要的?

4

3 回答 3

7

如果您正在寻找更自动化的路由,这将是 Laravel 4 方式:

路线:

Route::controller('users', 'UsersController');

控制器(在本例中为 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 所提到的,以冗长的方式进行操作有一些好处。除了他链接的优秀文章之外,您还可以为每条路线创建一个名称,例如:

Route::get("users", array(
    "as"=>"dashboard",
    "uses"=>"UsersController@getIndex"
));

然后在您的应用程序中创建 url 时,使用帮助程序生成指向命名路由的链接

$url = URL::route('dashboard');

然后,链接在未来不会受到控制器/操作更改的影响。

您还可以直接生成指向仍然适用于自动路由的操作的链接。

$url = URL::action('UsersController@getIndex');
于 2013-08-12T06:16:34.973 回答
6
应用程序\
    控制器\
        行政\
           管理员控制器.php
        索引控制器.php
Route::get('/admin/{controller?}/{action?}', function($controller='Index', $action='index'){
        $controller = ucfirst($controller);
        $action = $action . 'Action';
        return App::make("Admin\\{$controller}Controller")->$action();
    });

Route::get('/{controller?}/{action?}', function($controller='Index', $action='index'){
        $controller = ucfirst($controller);
        $action = $action . 'Action';
        return App::make("{$controller}Controller")->$action();
    });
于 2014-07-17T13:12:41.133 回答
0

我来自 .Net 世界,路由通常完成:

/{Controller}/{action}/{id}

看起来像:

/Products/Show/1 OR /Products/Show/Beverages

在 Laravel 中,我像这样完成此路由:

Route::get('/{controller?}/{action?}/{id?}', function ($controller='Home', $action='index', $id = null) {
    $controller = ucfirst($controller);
    return APP::make("{$controller}Controller")->$action($id);
});

控制器大致如下所示:

class ProductsController extends BaseController {
    public function Show($id) {
        $products = array( 1 => array("Price" => "$600","Item" => "iPhone 6"),
                           2 => array("Price" => "$700", "Item" => "iPhone 6 Plus") );

        if ($id == null) {
            echo $products[1]["Item"];
        } else {
            echo $products[$id]["Item"];
        }

    }
}
于 2014-09-21T22:52:42.627 回答