laravel / ideas

Issues board used for Laravel internals discussions.
939 stars 28 forks source link

[Proposal] route binding improvement #1191

Open Grummfy opened 6 years ago

Grummfy commented 6 years ago

Hello, today if we have an eloquent model we simply bind (if specific needs) it to the route or just do anything and laravel will do the work perfectly. It's simple and very helpful.

Today, more and more people use value object (or other class) for a lot of things. It could be very helpful to have something similar.

Three way of doing this, pop in my mind:

  1. Global binding like today with Route::bind() => it's working and it's ok
  2. a binding for a specific group/route to avoid a "contamination" of the other route => it would be nice, but not sure it so useful, but the idea popup while redacting this issue.
  3. the most interesting part : autobinding like for the model through an interface similar to \Illuminate\Contracts\Routing\UrlRoutable but with just the resolveRouteBinding(). This method should be static to avoid an instantiation of the object (if we use a value object, it will break there).

Thanks

Patryk27 commented 6 years ago

I don't understand what you mean - could you please provide some code example?

BertvanHoekelen commented 4 years ago

I also think this would be great! Especially when using enums.

You now get the Unresolvable dependency resolving [Parameter #0 [ <required> array $values ]] in class SomeValueObject:

Example:

use Illuminate\Contracts\Routing\UrlRoutable;

class SomeValueObject implements UrlRoutable
{
    public int $id;

    public function __construct(array $values)
    {
        $this->id = $values['id'];
    }

    public function resolveRouteBinding($value)
    {
        if ($value === 'valid') {
            return new self(['id' => $value]);
        }

        return null;
    }

    public function getRouteKey()
    {
        return $this->id;
    }

    public function getRouteKeyName(): string
    {
        return 'id';
    }
}

Route:


Route::get('/foo/{some}', function (SomeValueObject $foobar) {
   dd('never getting here :(');
});

If resolveRouteBinding was static it would just skip the constructor meaning you won't get the exception.