Lumen中的隐式路由模型绑定?

Rob*_*Rob 5 php laravel lumen

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

反正有没有启用这个?

$app->get('/users/{user}', 'UsersController@get');
Run Code Online (Sandbox Code Playgroud)

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

Moh*_*rib 8

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

流明路由绑定

这个需要 :

php >= 7.1
Lumen 5.* || 6.*
Run Code Online (Sandbox Code Playgroud)

它支持显式绑定:

$binder->bind('user', 'App\User');
Run Code Online (Sandbox Code Playgroud)

隐式绑定:

$binder->implicitBind('App\Models');
Run Code Online (Sandbox Code Playgroud)

和复合结合:(绑定多个通配符一起,在类似的情况下posts\{post}\comments\{comment},你就可以将其绑定到一个可调用,将解决PostComment相关文章)

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

    return [$post, $comment];
});
Run Code Online (Sandbox Code Playgroud)

也可以与其他类一起使用,例如Repositories

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

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

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

您可以在存储库类中的何处执行以下操作:

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


mac*_*air 5

我最近遇到了同样的问题,并怀疑这是可能的。Lumen 5.2 不使用 Illuminate 路由器,而是使用FastRoute有关此处差异的更多信息 但是,如果可以选择,应该可以编写自定义中间件。

  • 决定为 Laravel 转储 Lumen,太头疼了。 (2认同)