3 namespace Drupal\Core\DependencyInjection;
5 use Symfony\Component\DependencyInjection\ContainerInterface;
8 * Provides dependency injection friendly methods for serialization.
10 trait DependencySerializationTrait {
13 * An array of service IDs keyed by property name used for serialization.
17 protected $_serviceIds = [];
22 public function __sleep() {
23 $this->_serviceIds = [];
24 $vars = get_object_vars($this);
25 foreach ($vars as $key => $value) {
26 if (is_object($value) && isset($value->_serviceId)) {
27 // If a class member was instantiated by the dependency injection
28 // container, only store its ID so it can be used to get a fresh object
29 // on unserialization.
30 $this->_serviceIds[$key] = $value->_serviceId;
33 // Special case the container, which might not have a service ID.
34 elseif ($value instanceof ContainerInterface) {
35 $this->_serviceIds[$key] = 'service_container';
40 return array_keys($vars);
46 public function __wakeup() {
47 // Tests in isolation potentially unserialize in the parent process.
48 if (isset($GLOBALS['__PHPUNIT_BOOTSTRAP']) && !\Drupal::hasContainer()) {
51 $container = \Drupal::getContainer();
52 foreach ($this->_serviceIds as $key => $service_id) {
53 $this->$key = $container->get($service_id);
55 $this->_serviceIds = [];