代码拉取完成,页面将自动刷新
https://gitee.com/gordensong/laravel-autowire
对于声明了 Autowire
注解的类,调用 autowire($class)
可以自动初始化声明 Autowire
注解的属性.
属性自动绑定不限于单元测试使用,Repository, Service, Action 同样可以使用。
注意:不要循环引用注解属性。
<?php
use GordenSong\Laravel\Support\Autowire;
#[Autowire]
class Human
{
#[Autowire]
public ?Head $head = null;
}
#[Autowire]
class Head
{
#[Autowire]
public ?Mouth $mouth = null;
}
class Mouth
{
public ?Teeth $teeth = null;
}
class Teeth
{
}
<?php
namespace Tests;
class HelperTest extends TestCase
{
public function test_autowire()
{
/** @var Human $cat */
$cat = autowire(Human::class);
self::assertNotNull($cat);
self::assertNotNull($cat->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);
}
}
<?php
namespace Tests;
use GordenSong\Laravel\Support\Autowire;
use GordenSong\Laravel\Support\AutowireTrait;
class NotRecursiveAutowireTest extends TestCase
{
// 第一步:引用 Trait use AutowireTrait
use AutowireTrait;
protected function setUp(): void
{
parent::setUp();
// 第二步: $this->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);
}
}
<?php
namespace Tests;
use GordenSong\Laravel\Support\Autowire;
use GordenSong\Laravel\Support\AutowireTrait;
class RecursiveAutowireTest extends TestCase
{
use AutowireTrait; // 1.
protected function setUp(): void
{
parent::setUp();
$this->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
autowire($class)
等价于 app($class)
function autowire(string $class, bool $recursive = false) : mixed
function autowireProperties(object $object, bool $recursive = false)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。