"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Trying to get into laravel dependency injection

Trying to get into laravel dependency injection

Published on 2024-08-21
Browse:535

Trying to get into laravel dependency injection

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;
    }
}

And.. That means if I will do laravel "right", it lets me to drop "nwidard/larave-modules" Module and its overrides any part of code ?

Release Statement This article is reproduced at: https://dev.to/blinkinglight/trying-to-get-into-laravel-dependency-injection-160p?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3