From 93df0a9be406151e7e1818ad3ce1c6cb3c8aad32 Mon Sep 17 00:00:00 2001 From: twent Date: Tue, 11 Jul 2023 20:31:45 +0300 Subject: [PATCH] add: simple DI container with test --- Makefile | 5 +++- composer.json | 2 +- core/DI/Contracts/Container.php | 17 +++++++++++++ core/DI/GenericContainer.php | 29 +++++++++++++++++++++++ tests/Feature/DI/Foo.php | 9 +++++++ tests/Feature/DI/GenericContainerTest.php | 22 +++++++++++++++++ 6 files changed, 82 insertions(+), 2 deletions(-) create mode 100644 core/DI/Contracts/Container.php create mode 100644 core/DI/GenericContainer.php create mode 100644 tests/Feature/DI/Foo.php create mode 100644 tests/Feature/DI/GenericContainerTest.php diff --git a/Makefile b/Makefile index a76b6f7..7405677 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,10 @@ install: composer install --ignore-platform-reqs format: - vendor/bin/phpcs && vendor/bin/phpcbf + vendor/bin/phpcs + +format-fix: + vendor/bin/phpcbf analyse: vendor/bin/phpinsights analyse -n diff --git a/composer.json b/composer.json index a072d8b..c2a40e0 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,7 @@ }, "autoload-dev": { "psr-4": { - "Tests\\": "tests/" + "Tests\\Twent\\Framework\\": "tests/" } }, "require": { diff --git a/core/DI/Contracts/Container.php b/core/DI/Contracts/Container.php new file mode 100644 index 0000000..32909ad --- /dev/null +++ b/core/DI/Contracts/Container.php @@ -0,0 +1,17 @@ + $className + * @return TClassName + */ + public function get(string $className): object; +} diff --git a/core/DI/GenericContainer.php b/core/DI/GenericContainer.php new file mode 100644 index 0000000..656688a --- /dev/null +++ b/core/DI/GenericContainer.php @@ -0,0 +1,29 @@ +definitions[$className] = $definition; + + return $this; + } + + /** + * @inheritDoc + */ + public function get(string $className): object + { + $definition = $this->definitions[$className]; + + return $definition(); + } +} diff --git a/tests/Feature/DI/Foo.php b/tests/Feature/DI/Foo.php new file mode 100644 index 0000000..921ebe3 --- /dev/null +++ b/tests/Feature/DI/Foo.php @@ -0,0 +1,9 @@ +register(Foo::class, static fn() => new Foo()); + + $foo = $container->get(Foo::class); + + $this->assertInstanceOf(Foo::class, $foo); + } +}