The article "Laravel Attributes Overview: What and How to Use" decried the possibility of simplifying dependency injection with attributes. However, it is not necessary to limit yourself to only standard Laravel attributes. You can create your own attribute that will perform the task you want.
An example of creating an attribute that automatically pulls values from the configuration, i.e. to be similar to a helper config():
First, let's create a class MyConfigthat implements the interface Illuminate\Contracts\Container\ContextualAttribute. This is necessary for the container to work with it.
namespace App\Attributes;
use Attribute;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Container\ContextualAttribute;
#[Attribute(Attribute::TARGET_PARAMETER)]
class MyConfig implements ContextualAttribute
{
public function __construct(
public string $key,
) {}
public static function resolve(self $attribute, Container $container)
{
return $container->make('config')->get($attribute->key);
}
}
Now the attribute #[MyConfig] is ready. Use it, for example, to automatically substitute the application name in the controller:
namespace App\Http\Controllers;
use App\Attributes\MyConfig;
class ExampleController extends Controller
{
public function __construct(
#[MyConfig('app.name')] protected string $appName
) {}
public function show(): string
{
return "Имя приложения: {$this->appName}";
}
}
Of course, Laravel already has the , Configbut the main thing is that this example is easy to adapt to other tasks, such as substitution of API keys, flags, etc.