首页  >  文章  >  后端开发  >  尝试进入 Laravel 依赖注入

尝试进入 Laravel 依赖注入

WBOY
WBOY原创
2024-08-12 06:59:32740浏览

Trying to get into laravel dependency injection

<?php

use App\Models\User;

test('Action', function () {

    app()->singleton(ClassInterface::class, T1Impl::class);
    $out1 = app(ClassInterface::class)();
    $this->assertEquals("T1?", $out1);

    app()->bind(ClassInterface::class, T2Impl::class);

    $out2 = app(ClassInterface::class)();
    $this->assertEquals("T2!", $out2);

    app()->bind(T1Impl::class, T2Impl::class);
    $out3 = app(T1Impl::class)();
    $this->assertEquals("T2!", $out3);



    app()->bind(T2Impl::class, T3Impl::class);
    app()->bind(T1Impl::class, T2Impl::class);
    app()->singleton(ClassInterface::class, T1Impl::class);
    $out4 = app(ClassInterface::class)();
    $this->assertEquals("T3!", $out4);


    $user = User::factory()->create(['name'=>'Tomas']);
    $out5 = app(T4::class, ['user'=>$user])();
    $this->assertEquals("Tomas", $out5);
});

interface ClassInterface {
    public function __invoke();
}

class T1Impl implements ClassInterface {
    public function __invoke() {
        return "T1?";
    }
}

class T2Impl implements ClassInterface {
    public function __invoke() {
        return "T2!";
    }
}


class T3Impl implements ClassInterface {
    public function __invoke() {
        return "T3!";
    }
}

class T4 {
    public function __construct(
        public User $user
    ){}

    public function __invoke() {
        return $this->user->name;
    }
}

并且..这意味着如果我“正确”地执行laravel,它可以让我删除“nwidard/larave-modules”模块并覆盖代码的任何部分?

以上是尝试进入 Laravel 依赖注入的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn