Resovable trait for Laravel container

Resovable trait for Laravel container

ยท

2 min read

If you really work on Laravel, you're gonna deal a lot of times with its Container and, probably, you often will need to resolve something from it, with a syntax like this:

$service = resolve(MyService::class);

// or

$service = App::make(MyService::class, ['id' => 3]);

In my case I'm doing this a lot of times, particularly when writing tests and, because we don't have generics in PHP, the IDE won't know what resolve or App::make return, therefore you must rely on tools like IntelliSense or Intelephense with a PHPDoc:

/** @var MyService */
$service = App::make(MyService::class, ['id' => 3]);

This is pretty straightforward, right? But I find it annoying in the long run, therefore I created this little yet powerful trait to resolve something from the container without any additional PHPDoc and just using the standard PHP typed syntax:

<?php

namespace App\Traits;

use Illuminate\Support\Facades\App;

trait Resolvable
{
    /**
     * Resolve itself from the container.
     */
    public static function resolve(array $parameters = []): static
    {
        return App::make(static::class, $parameters);
    }
}

Then, in your class, you can just "include" it and the magic is ready ๐Ÿช„ Thanks to the static keyword as return type, the IDE will automatically know what's being returned and we don't need anymore those PHPDoc.

use App\Traits\Resolvable;

class MyService
{
    use Resolvable;

    public function __construct()
    {
        // Something
    }

    public function sayHi(): string
    {
        return 'Hello there';
    }
}

// Somewhere else
$greet = MyService::resolve()->sayHi();
ย