PHP-DI - Differences Between Factories and Objects

PHP-DI allows some methods to define injections, including factories and objects: http://php-di.org/doc/php-definitions.html .

Plants

TestClass::class => function () {
   return new TestClass('param');
}

An instance TestClassis created lazily only when necessary.

The objects

TestClass::class => DI\object()->constructor('param')

If you use objects, is the tape also lazy to create?

If so, what is the difference between factories and facilities?

+4
source share
2 answers

The PHP-DI author here seems to have some confusion (given the question and how the other answer is wrong). I improved the documentation, I hope this clarifies the situation: ec8120ee .

To answer your questions:

If you use objects, is the tape also lazy to create?

, , object() .

, ?

. , object().

.

+1

EDIT: , . !


, PHP-DI, .

PHP-DI factory, , ( , Ocramius Proxy Manager).

PHP-DI DI\object() . , , . , , . . :

$builder = new DI\ContainerBuilder();
$builder->addDefinitions([
    TestClass::class => DI\object()->constructor('param')
]);
$container = $builder->build();

$container TestClass.

, ( , . ), Ocramius Proxy Manager, ->lazy():

$builder = new DI\ContainerBuilder();
$builder->addDefinitions([
    TestClass::class => DI\object()->constructor('param')->lazy()
]);
$container = $builder->build();

() -, .. . Ocramius Proxy Manager - , , .

PHP-DI factory . , , , . , DI\object() , . DI\object(), , DI\factory(), .

PHP-DI , , , :

TestClass::class => DI\factory(function() {
    return new TestClass('param');
})->scope(DI\Scope::PROTOTYPE);

, ->scope(). , PROTOTYPE ( ) SINGLETON ( ). SINGLETON, , , .


  • factory, .
  • , ,
  • , , . , : a) ; ) , , ) - . (, , ).
+1

Source: https://habr.com/ru/post/1684076/


All Articles