# laravel-autowire **Repository Path**: gordensong/laravel-autowire ## Basic Information - **Project Name**: laravel-autowire - **Description**: 基于 laravel,Autowire 注解的方式自动注入。 - **Primary Language**: PHP - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 2 - **Forks**: 0 - **Created**: 2021-08-26 - **Last Updated**: 2024-03-08 ## Categories & Tags **Categories**: Uncategorized **Tags**: autowire, ioc, 依赖注入 ## README https://gitee.com/gordensong/laravel-autowire # 自动绑定类属性 1. 对于声明了 `Autowire` 注解的类,调用 `autowire($class)` 可以自动初始化声明 `Autowire` 注解的属性. 2. 属性自动绑定不限于单元测试使用,Repository, Service, Action 同样可以使用。 3. 注意:不要循环引用注解属性。 ## 直接上栗子 ### Human ```php head); self::assertNull($cat->head->mouth); } public function test_autowire_recursive() { /** @var Human $cat */ $cat = autowire(Human::class, true); self::assertNotNull($cat); self::assertNotNull($cat->head); self::assertNotNull($cat->head->mouth); self::assertNull($cat->head->mouth->teeth); } } ``` ### TestCase 自动注入 ```php autowireProperties(); 绑定值为空的属性 $this->autowireProperties(); // 不递归绑定 } // 第三步:使用注解 #[Autowire] private ?Human $human = null; public function test_auto_wire_head_is_null() { self::assertNotNull($this->human); self::assertNull($this->human->head); } } ``` ### TestCase 递归注入 ```php autowireProperties(true); // 2. 递归绑定 } // 3. 使用注解 #[Autowire] private ?Human $cat = null; public function test_auto_wire_head_is_null() { self::assertNotNull($this->cat); self::assertNotNull($this->cat->head); self::assertNotNull($this->cat->head->mouth); self::assertNull($this->cat->head->mouth->teeth); // teeth 未加注解 } } ``` ## 安装 ``` composer require --dev gordensong/laravel-autowire ``` ## 说明 ### Function #### 1. `autowire($class)` 等价于 `app($class)` ```php function autowire(string $class, bool $recursive = false) : mixed ``` #### 2. 自动绑定属性值, 对象内部使用。 ```php function autowireProperties(object $object, bool $recursive = false) ```