File: services.yml
services:
object_container:
class: ObjectContainer
File: lib/a/b/c/ObjectContainer.php
class ObjectContainer
{
protected $objects = array();
public function __construct()
{
$this->initialize();
$data = date('Y-m-d H:i:s') . ': I was born!' . "\n";
file_put_contents('C:/diary.log', $data, FILE_APPEND | LOCK_EX);
}
public function initialize()
{
$this->objects = array();
}
public function __get($name)
{
return $this->objects[$name];
}
public function __set($name, $value)
{
$this->objects[$name] = $value;
}
public function getObjects()
{
return $this->objects;
}
}
# Clear cache
php symfony cc
In actions:
$s1 = $this->getService('object_container');
$s1->anyVar = $anyValue;#object, array, int, string …
$s2 = $this->getService('object_container');
echo $s2->anyVar;
#$s2 is $s1, no more ObjectContainer is constructed!