我正在尝试在 Lumen 中使用隐式路由模型绑定,但似乎它不起作用。
有没有办法启用它?
$app->get('/users/{user}', 'UsersController@get');
它只是返回user
中的值,但它不是类型暗示它并返回模型。
我创建了一个软件包来添加对 Lumen 中route-model-binding
的支持,请在此处查看:
流明路由绑定
它需要:
php >= 7.1
Lumen 5.* || 6.*
它支持显式绑定:
$binder->bind('user', 'AppUser');
隐式绑定:
$binder->implicitBind('AppModels');
和复合绑定:(将多个通配符绑定在一起,在posts{post}comments{comment}
这样的情况下,您将能够将其绑定到可调用对象,该可调用对象将解决与帖子相关的Post
和Comment
)
$binder->compositeBind(['post', 'comment'], function($postKey, $commentKey) {
$post = AppPost::findOrFail($postKey);
$comment = $post->comments()->findOrFail($commentKey);
return [$post, $comment];
});
也可以与其他类一起使用,例如Repositories
:
// Add a suffix to the class name
$binder->implicitBind('AppRepositories', '', 'Repository');
可以在存储库上使用自定义方法:
// Use a custom method on the class
$binder->implicitBind('AppRepositories', '', 'Repository', 'findForRoute');
在存储库类中的位置可以执行以下操作:
public function findForRoute($val)
{
return $this->model->where('slug', $val)->firstOrFail();
}
我最近遇到了同样的问题,并怀疑这是否可能。Lumen 5.2不使用Illuminate路由器,而是使用FastRoute。有关差异的更多信息,请单击此处但是,如果可以选择,应该可以编写自定义中间件。