bardiz12/auto-inject-for-laravel
最新稳定版本:v1.0.1
Composer 安装命令:
composer require bardiz12/auto-inject-for-laravel
包简介
Automatic dependency injection for laravel
README 文档
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
统计信息
- 总下载量: 133
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-05-08