Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## [Unreleased]

### Changed

- Unused services are freed from memory

### Removed

- Using a `string` as a service name
Expand Down
29 changes: 24 additions & 5 deletions src/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,23 @@
use Innmind\Immutable\{
Map,
Sequence,
Maybe,
Str,
};

final class Container
{
/** @var array<string, object> */
private array $services = [];

/**
* @psalm-mutation-free
*
* @param Map<Service, callable(self): object> $definitions
* @param Sequence<Service> $building
* @param Map<Service, \WeakReference<object>> $services
*/
private function __construct(
private Map $definitions,
private Sequence $building,
private Map $services,
) {
}

Expand Down Expand Up @@ -75,7 +75,22 @@ public function __invoke(Service $name): object
* @psalm-suppress InvalidPropertyAssignmentValue
* @var T
*/
return $this->services[\spl_object_hash($name)] ??= $definition($this);
return $this
->services
->get($name)
->flatMap(static fn($service) => Maybe::of($service->get()))
->match(
static fn($service) => $service,
function() use ($name, $definition) {
$service = $definition($this);
$this->services = $this->services->put(
$name,
\WeakReference::create($service),
);

return $service;
},
);
} finally {
$this->building = $this->building->dropEnd(1);
}
Expand All @@ -88,6 +103,10 @@ public function __invoke(Service $name): object
*/
public static function of(Map $definitions): self
{
return new self($definitions, Sequence::of());
return new self(
$definitions,
Sequence::of(),
Map::of(),
);
}
}
16 changes: 16 additions & 0 deletions tests/ContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,20 @@ public function testEnumCaseCanBeUsedToReferenceAService()

$this->assertSame($expected, $container(Services::a));
}

public function testServicesAreFreedFromMemoryWhenUnused()
{
$called = 0;
$container = Builder::new()
->add(Services::name, static function() use (&$called) {
++$called;

return new \stdClass;
})
->build();

$container(Services::name);
$this->assertInstanceOf(\stdClass::class, $container(Services::name));
$this->assertSame(2, $called);
}
}
Loading