prokofiev's avatar

DI recursion

It so happened that I created two classes that have mutual dependencies. I can’t detect this in any way, so is there any way to catch such an error?

The Docker container stops with status 255, and there are no logs - neither in the container nor in the framework's storage.

How to reproduce?

Just create two classes like that

<?php
namespace App\Services;
class ClassOne
{
    public function __construct(
        protected ClassTwo $class,
    ) {
        //
    }
}

and another one

<?php
namespace App\Services;
class ClassTwo
{
    public function __construct(
        protected ClassOne $class,
    ) {
        //
    }
}

Then make command and bind the classes

<?php
namespace App\Console\Commands;

use App\Services\ClassOne;
use App\Services\ClassTwo;
use Illuminate\Console\Command;

class AnyCommand extends Command
{
    protected $signature = 'any:command';

    public function handle(ClassOne $one, ClassTwo $two)
    {
        //
    }
}

And run command:

docker compose exec app php artisan any:command

There nothing in console, just exit, Command echo $? returns 255

0 likes
6 replies
tykus's avatar

What is the reason for such tightly coupled classes; are you missing an abstraction?

1 like
prokofiev's avatar

@tykus never mind of abstraction, I've just tried to show the example of issue

Trouble is the framework doesn't catch the exception

krisi_gjika's avatar

@prokofiev why would it? it's a infinite recursion exception on the language level, not a framework level. You can likely replicate the same issue without DI.

kokoshneta's avatar

@prokofiev What exception? What error?

You’ve deliberately structured your classes so as to lead to infinite recursion, so the framework/interpreter can only assume that was your intention. The only real error is the structure itself.

tykus's avatar

@prokofiev

I've just tried to show the example of issue

And what do you expect will happen if you try to resolve instances from the Container that recursively instantiate each other?

prokofiev's avatar

@tykus I expect any exception that tells me there is the error. I don't expect just "ok, I just gonnaway bro"

Have a look at symfony, I've implemented the same classes and caught the exception:

Circular reference detected for service "App\Service\ClassOne", path: "App\Service\ClassOne -> App\Service\ClassTwo -> App\Service\ClassOne". That thing I wanna see in Laravel

Please or to participate in this conversation.