首页 > 解决方案 > 使用 Route 对象从控制器方法内部获取路由参数是否被认为是一种不好的做法?[拉拉维尔]

问题描述

我有多个路由可以解析为单个控制器方法。我Route用来获取路由参数,因为 Laravel 按照定义的顺序将参数传递给方法。尽管该Route方法有效,但它增加了我们单元测试的复杂性。有什么建议么?

<?php

// routes/api.php

$router->get('/test/{another_example_param}', ['uses' => 'ExampleController@show']);
$router->get('/test/{example_param}/thing/{another_example_param}', ['uses' => 'ExampleController@show']);
$router->get('/testing/{example_param}', ['uses' => 'ExampleController@show']);
<?php

// ExampleController.php

use Illuminate\Routing\Controller
use Illuminate\Routing\Route;

class ExampleController extends Controller {
  // Explicitly defining route parameters
  public function show(string $example_param, string $another_example_param) {
    echo "example param: $example_param";
    echo "another_example param: $another_example_param";
  }  

  // Extracting route params from Route approach
  public function showAlternate(Route $route) {
    $example_param = $route->example_param;
    $another_example_param = $route->another_example_param;

    echo "example param: $example_param";
    echo "another_example param: $another_example_param";    
  }  
}

标签: laravellaravel-6

解决方案


推荐阅读