bardiz12 / auto-inject-for-laravel
Automatic dependency injection for laravel
v1.0.1
2025-05-13 10:36 UTC
Requires (Dev)
- laravel/framework: ^11.0.0|^12.13
- orchestra/testbench: ^10.2
- pestphp/pest: ^3.8
- pestphp/pest-plugin-laravel: ^3.2
README
Inspired by php-di's #[Inject()]
attribute, i created a simple package to automatically inject dependency to php class's properties. This package is also support lazy load the dependency by proxying the access to class via Laravel's app() helper.
Installation
composer require bardiz12/auto-inject-for-laravel
Usage
-
Use Auto Inject trait and add autoInject method in your constructor
<?php namespace ...; use Bardiz12\AutoInjectForLaravel\AutoInjectable; class MyClass { use AutoInjectable; ... public function __construct() { $this->autoInject(); } }
-
Add Attribute to your class Property
- Reading abstract from property's type
<?php namespace ...; use Bardiz12\AutoInjectForLaravel\Attributes\Inject; use Bardiz12\AutoInjectForLaravel\AutoInjectable; class MyClass { use AutoInjectable; #[Inject()] protected MyDependency $myDependency; ... public function __construct() { $this->autoInject(); } }
- or, you can use custom string abstract by passing parameter to the Inject attribute
<?php namespace ...; use Bardiz12\AutoInjectForLaravel\Attributes\Inject; use Bardiz12\AutoInjectForLaravel\AutoInjectable; class MyClass { use AutoInjectable; #[Inject(abstract: MyDependency::class)] /** * My Dependency * * @var MyDependency */ protected $myDependency; ... public function __construct() { $this->autoInject(); } }
- Reading abstract from property's type
-
To Use Lazy load, you can add lazy parameter to the Inject attribute. If the lazy parameter is not provided but the property has Lazy type using Union Type, it will be loaded as lazy Dependency.
<?php namespace ...; use Bardiz12\AutoInjectForLaravel\Attributes\Inject; use Bardiz12\AutoInjectForLaravel\AutoInjectable; use Bardiz12\AutoInjectForLaravel\Proxy\Lazy; class MyClass { use AutoInjectable; #[Inject(lazy: true)] /** * * * @var MyDependency|Lazy<MyDependency> */ protected MyDependency|Lazy $myDependency; ... public function __construct() { $this->autoInject(); } }
or