I've been changing my Controllers and helper classes to use dependency injection, and it seems I've got my helper classes stuck in an infinite loop.
Below is my custom ServiceProvider and the two sample helper classes. As you can see, they inject each other, so they keep going back and forth.
What's the solution to this issue? What mistake do I seem to be making? What can I do so that I can run tests on helper classes like General
and Person
, while mocking the helper classes that are called from inside of them?
One way that I guess could work is in my ServiceProvider, do the following:
if (isset($appmade->General)) {
// inject the General app that's already instantiated
} else {
$abc = app::make('\Lib\MyOrg\General');
$appmade->General = $abc;
}
Is that the correct way?
// /app/providers/myorg/MyOrgServiceProvider.php
namespace MyOrg\ServiceProvider;
use Illuminate\Support\ServiceProvider;
class MyOrgServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('\Lib\MyOrg\General', function ($app) {
return new \Lib\MyOrg\General(
$app->make('\Lib\MyOrg\Person'),
$app->make('\App\Models\User')
);
});
$this->app->bind('\Lib\MyOrg\Person', function ($app) {
return new \Lib\MyOrg\Person(
$app->make('\Lib\MyOrg\General'),
$app->make('\App\Models\Device')
);
});
}
}
// /app/libraries/myorg/general.php
namespace Lib\MyOrg;
use App\Models\User;
use Lib\MyOrg\Person;
class General
{
protected $model;
protected $class;
public function __construct(Person $personclass, User $user)
{
}
}
// /app/libraries/myorg/person.php
namespace Lib\MyOrg;
use App\Models\Device;
use Lib\MyOrg\General;
class Person
{
protected $model;
protected $class;
public function __construct(General $generalclass, Device $device)
{
}
}