-
-
Save lisachenko/6345683 to your computer and use it in GitHub Desktop.
<?php | |
use Warlock\Annotation\Autowired; | |
class Example | |
{ | |
/** | |
* @Autowired("logger", required=true) | |
* @var LoggerInterface | |
*/ | |
protected $logger = null; // no public properties for property injection, only protected services | |
// no constructor injection | |
// no setter injection | |
public function test() | |
{ | |
$this->logger->info("Logger injected only here due to request to the this->logger"); | |
echo 'Yay'; | |
} | |
} |
<?php | |
// somewhere at the kernel ... | |
$container = new DiContainer(); | |
// our code, this can be plain entities (POPO) that not defined in the container | |
$instance = new Example(); // No services injection at all! | |
$instance->test(); // logger will be requested and injected from the container automatically by Warlock |
Nice idea!
http://jmsyst.com/bundles/JMSDiExtraBundle/master/annotations
implementation of the idea already exists
Just discovered implementation of @Autowired using AOP - looks nice and simple from point view of source code: https://github.com/lisachenko/warlock/blob/master/src/Warlock/Aspect/AutowiringAspect.php
What is the performance impact of this approach?
As I understand DIC injects dependent services on the first parent service request (construction)
Is AOP approach injects service exactly at the moment when parent service tries to access dependent?
@vdroznik Yes, you are right ) Each modern DI-container creates all dependencies for service at once. Some of them use a trick with LazyProxy pattern to prevent the construction of whole the dependency graph, but only the Warlock will inject a dependency only when it is really needed in the concrete method. This will reduce a typical boilerplate code for constructors and will allow for better performance.
It's possible to inject services everywhere, for example, into entities or even into compiled Twig templates :)
Huh, didn't think about injection into entities. Interesting.
Usually this is a bad practice, but sometimes this could be really useful to make the code transparent and easy.
That's crazy! This is new to me. Will have to research Autowired.