【问题标题】:Implicit route model binding in Lumen?Lumen中的隐式路由模型绑定?
【发布时间】:2016-06-10 18:49:40
【问题描述】:

我正在尝试在 Lumen 中使用隐式路由模型绑定,但似乎不起作用。

有没有办法开启这个功能?

$app->get('/users/{user}', 'UsersController@get');

它只是返回 user 中的值,而不是类型提示并返回模型。

【问题讨论】:

    标签: php laravel lumen


    【解决方案1】:

    我创建了一个包以在 Lumen 中添加对 route-model-binding 的支持,请在此处查看:

    Lumen Route Binding

    需要:

    php >= 7.1
    Lumen 5.* || 6.*
    

    它支持显式绑定:

    $binder->bind('user', 'App\User');
    

    隐式绑定:

    $binder->implicitBind('App\Models');
    

    复合绑定:(将多个通配符绑定在一起,在posts\{post}\comments\{comment} 这样的情况下,您将能够将其绑定到一个可调用的对象,该可调用对象将解析与帖子相关的Post 和Comment)

    $binder->compositeBind(['post', 'comment'], function($postKey, $commentKey) {
        $post = \App\Post::findOrFail($postKey);
        $comment = $post->comments()->findOrFail($commentKey);
    
        return [$post, $comment];
    });
    

    也可以与Repositories 等其他类一起使用:

    // Add a suffix to the class name
    $binder->implicitBind('App\Repositories', '', 'Repository');
    

    可以在存储库上使用自定义方法:

    // Use a custom method on the class
    $binder->implicitBind('App\Repositories', '', 'Repository', 'findForRoute');
    

    您可以在存储库类的哪个位置进行操作:

    public function findForRoute($val)
    {
        return $this->model->where('slug', $val)->firstOrFail();
    }
    

    【讨论】:

      【解决方案2】:

      我最近遇到了同样的问题,并且怀疑这是否可能。 Lumen 5.2 不使用 Illuminate 路由器,而是使用 FastRoute。 more info on the differences here 但是,如果可以的话,应该可以编写自定义中间件。

      【讨论】:

      • 决定为 Laravel 抛弃 Lumen,实在是太头疼了。
      • 也许你可以试试这个包packagist.org/packages/mmghv/lumen-route-binding,
      • @Rob 同意。如果你只是拼凑一个简单的 JSON API,Laravel 就很棒,但只要你想要任何“有用”的东西(表单请求、路由模型绑定等),那么你也可以使用 Laravel。您可以禁用不需要的服务提供者(会话、视图等)。
      猜你喜欢
      • 2019-01-10
      • 1970-01-01
      • 2017-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 2016-04-15
      • 2018-12-17
      相关资源
      最近更新 更多