Skip to content

Instantly share code, notes, and snippets.

@lisachenko
Last active December 21, 2015 18:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lisachenko/6345683 to your computer and use it in GitHub Desktop.
Save lisachenko/6345683 to your computer and use it in GitHub Desktop.
Autowiring preview
<?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
@lisachenko
Copy link
Author

@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 :)

@vdroznik
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment