Skip to content

Commit

Permalink
add: simple DI container with test
Browse files Browse the repository at this point in the history
  • Loading branch information
twent committed Jul 11, 2023
1 parent 5224770 commit 93df0a9
Show file tree
Hide file tree
Showing 6 changed files with 82 additions and 2 deletions.
5 changes: 4 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
"Tests\\Twent\\Framework\\": "tests/"
}
},
"require": {
Expand Down
17 changes: 17 additions & 0 deletions core/DI/Contracts/Container.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Twent\Framework\DI\Contracts;

interface Container
{
public function register(string $className, callable $definition): self;

/**
* @template TClassName
* @param class-string<TClassName> $className
* @return TClassName
*/
public function get(string $className): object;
}
29 changes: 29 additions & 0 deletions core/DI/GenericContainer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace Twent\Framework\DI;

use Twent\Framework\DI\Contracts\Container;

final class GenericContainer implements Container
{
private array $definitions = [];

public function register(string $className, callable $definition): Container
{
$this->definitions[$className] = $definition;

return $this;
}

/**
* @inheritDoc
*/
public function get(string $className): object
{
$definition = $this->definitions[$className];

return $definition();
}
}
9 changes: 9 additions & 0 deletions tests/Feature/DI/Foo.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

namespace Tests\Twent\Framework\Feature\DI;

final class Foo
{
}
22 changes: 22 additions & 0 deletions tests/Feature/DI/GenericContainerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace Tests\Twent\Framework\Feature\DI;

use PHPUnit\Framework\TestCase;
use Twent\Framework\DI\GenericContainer;

final class GenericContainerTest extends TestCase
{
public function testContainer(): void
{
$container = new GenericContainer();

$container->register(Foo::class, static fn() => new Foo());

$foo = $container->get(Foo::class);

$this->assertInstanceOf(Foo::class, $foo);
}
}

0 comments on commit 93df0a9

Please sign in to comment.