<?php
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
class Foo
{
public function getFooString()
{
return 'foo';
}
}
class Bar
{
private $foo;
public function __construct(Foo $foo)
{
$this->foo = $foo;
}
public function getOutput()
{
return 'bar' . $this->foo->getFooString();
}
}
// the service container
$fooDefinition = new Definition('Foo');
$fooRef = new Reference('foo');
// adding foo definition is possible too
$barDefinition = new Definition('Bar', [$fooRef]);
$barDefinition->setPublic(true);
$containerBuilder = new ContainerBuilder();
$containerBuilder->setDefinition('foo', $fooDefinition);
$containerBuilder->setDefinition('bar', $barDefinition);
// call the new bar service with fo dependency
$bar = $containerBuilder->get('bar');
echo $bar->getOutput();