Answer the question
In order to leave comments, you need to log in
How to manage your own and third-party dependencies using an IoC container?
At the moment, there is a library where, for bad reasons, instances of dependency classes are created right in the constructor.
It is necessary to:
1. put all third-party dependencies in a container
2. put the library in a container
3. figure out how to inject dependencies into the library and its classes
4. use the class as before.
I don't understand how to use dependencies in my classes. So far, one thought came to mind - to use the main App class, which will be global in the NS library and then, using a singleton, get the container object in the constructor of dependent classes.
$app = new Illuminate\Container\Container();
$app->bind('app', $app);
$app->bind('log', $log);
class A extends SplObjectStorage
{
protected $log = null;
public function __construct()
{
//как я должен использовать контейнер, чтобы напрямую не передавать его в конструктор при вызове?
$this->log = new MongoLog();
}
}
class B extends A {}
class C extends A {}
$a = new A(); // т.е. оставить вызов и использование библиотеки таким, каков он есть
Answer the question
In order to leave comments, you need to log in
$app = new Illuminate\Container\Container();
$app->bind('app', $app);
$app->instance('log', $log);
$app->bind('MongoLog', 'log');
class A extends SplObjectStorage
{
protected $log;
public function __construct(MongoLog $log)
{
$this->log = $log;
}
}
class B extends A {}
class C extends A {}
$a = $app->make('A');
$b = $app->make('B');
$c = $app->make('C');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question