DEV Community

M
M

Posted on

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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 ?

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay