简体   繁体   中英

Implicit route model binding in Lumen?

I'm trying to use implicit route model binding in Lumen but seems it's not working.

Is there anyway to enable this?

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

It's just returning the value in user but it's not type hinting it and returning the model.

I created a package to add support for route-model-binding in Lumen, Check it out here :

Lumen Route Binding

It requires :

php >= 7.1
Lumen 5.* || 6.*

It supports Explicit binding :

$binder->bind('user', 'App\User');

Implicit binding :

$binder->implicitBind('App\Models');

And Composite binding : (bind more than one wildcard together, In situations like posts\\{post}\\comments\\{comment} you will be able to bind it to a callable that will resolve the Post and the Comment related to the post)

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

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

Also can work with other classes like Repositories :

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

Can use a custom method on the repository :

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

Where in the repository class you can do :

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

I ran into the same issue recently and doubt that it's possible. Lumen 5.2 does not use the Illuminate router but FastRoute instead. more info on the differences here However, it should be possible to write a custom middleware if that's an option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM