From a7e4f6614197b695bfdcab185a849035e9196706 Mon Sep 17 00:00:00 2001 From: Andrei Pisarevskii Date: Tue, 19 Mar 2024 00:37:17 +0300 Subject: [PATCH] Add auto-register the container. It helps get rid of errors related to different $container instances after autowiring. --- src/Container.php | 10 +++++++++- tests/ContainerTest.php | 12 ++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/Container.php b/src/Container.php index d439ca5..0537387 100644 --- a/src/Container.php +++ b/src/Container.php @@ -8,7 +8,7 @@ * Author Email: renakdup@gmail.com * Author Site: https://wp-yoda.com/en/ * - * Version: 0.2.3 + * Version: 0.2.4 * Source Code: https://github.com/renakdup/simple-php-dic * * Licence: MIT License @@ -95,6 +95,14 @@ class Container implements ContainerInterface { */ protected array $reflection_cache = []; + public function __construct() { + // Auto-register the container + $this->resolved = [ + self::class => $this, + ContainerInterface::class => $this, + ]; + } + /** * Set service to the container. Allows to set configurable services * using factory "function () {}" as passed service. diff --git a/tests/ContainerTest.php b/tests/ContainerTest.php index a47e028..7259961 100644 --- a/tests/ContainerTest.php +++ b/tests/ContainerTest.php @@ -96,14 +96,14 @@ public function test_get__create_not_bound_service() { self::assertEquals( new SimpleClass(), $this->container->get( SimpleClass::class ) ); } - public function test_get__check_singleton_for_not_bounded() { + public function test_get__singleton_check_for_not_bounded() { self::assertSame( $this->container->get( SimpleClass::class ), $this->container->get( SimpleClass::class ) ); } - public function test_get__check_changing_singleton_property() { + public function test_get__singleton_check_changing_property() { $this->container->set( $name = 'service', function () { $obj = new stdClass(); $obj->title = 'first title'; @@ -130,6 +130,14 @@ public function test_get__singleton_for_resolved_child_dependencies() { ); } + public function test_get__singleton_autoregister_container() { + $obj = $this->container->get( Container::class ); + $obj2 = $this->container->get( ContainerInterface::class ); + + self::assertSame( $this->container, $obj ); + self::assertSame( $this->container, $obj2 ); + } + public function test_get__autowiring() { $expected = new SimpleClass(); $this->container->set( $name = SimpleClass::class, SimpleClass::class );