Skip to content

Commit

Permalink
Add auto-register the container.
Browse files Browse the repository at this point in the history
It helps get rid of errors related to different $container instances after autowiring.
  • Loading branch information
renakdup committed Mar 18, 2024
1 parent f75877d commit a7e4f66
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
10 changes: 9 additions & 1 deletion src/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
* Author Email: [email protected]
* 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
Expand Down Expand Up @@ -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.
Expand Down
12 changes: 10 additions & 2 deletions tests/ContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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 );
Expand Down

0 comments on commit a7e4f66

Please sign in to comment.