【发布时间】:2016-06-10 18:49:40
【问题描述】:
我正在尝试在 Lumen 中使用隐式路由模型绑定,但似乎不起作用。
有没有办法开启这个功能?
$app->get('/users/{user}', 'UsersController@get');
它只是返回 user 中的值,而不是类型提示并返回模型。
【问题讨论】:
我正在尝试在 Lumen 中使用隐式路由模型绑定,但似乎不起作用。
有没有办法开启这个功能?
$app->get('/users/{user}', 'UsersController@get');
它只是返回 user 中的值,而不是类型提示并返回模型。
【问题讨论】:
我创建了一个包以在 Lumen 中添加对 route-model-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();
}
【讨论】:
我最近遇到了同样的问题,并且怀疑这是否可能。 Lumen 5.2 不使用 Illuminate 路由器,而是使用 FastRoute。 more info on the differences here 但是,如果可以的话,应该可以编写自定义中间件。
【讨论】: