我正在尝试在Lumen中使用隐式路由模型绑定,但似乎它不起作用。
无论如何都要启用它吗?
$app->get('/users/{user}', 'UsersController@get');
它只是返回user
中的值,但它不是键入提示并返回模型。
答案 0 :(得分:3)
我创建了一个包,用于在Lumen中添加对route-model-binding
的支持,请在此处查看:
需要:
php >= 5.4.0
Lumen 5.*
它支持显式绑定:
$binder->bind('user', 'App\User');
隐含约束:
$binder->implicitBind('App\Models');
和Composite绑定:(将多个通配符绑定在一起,在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();
}
您可以在存储库类中执行以下操作:
String
答案 1 :(得分:1)
我最近遇到了同样的问题并怀疑它是否可能。 Lumen 5.2不使用Illuminate路由器,而是使用FastRoute。 more info on the differences here 但是,应该可以编写自定义中间件,如果这是一个选项。