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

Implicit route model binding in Lumen?

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

有没有办法启用这个?

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

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

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

我创建了一个包以在 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} 等情况下,您将能够将其绑定到一个可调用的对象,该调用将解析 PostComment 与 post)

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

    return [$post, $comment];
});

也可以与其他 classes 一起使用,例如 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');

在存储库中的什么地方 class 你可以做:

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