Skip to content

Commit cef2a97

Browse files
Fedikvoronkovich
andauthored
Lazy Objects helper v2 (#67)
* Lazy Objects helper v2 * Apply suggestions from code review Co-authored-by: Oleg Voronkovich <oleg-voronkovich@yandex.ru> --------- Co-authored-by: Oleg Voronkovich <oleg-voronkovich@yandex.ru>
1 parent ead3826 commit cef2a97

File tree

2 files changed

+9
-13
lines changed

2 files changed

+9
-13
lines changed

Tests/ContainerSetupTest.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -327,9 +327,9 @@ static function () {
327327
public function testCreateLazyProxy()
328328
{
329329
$container = new Container();
330-
$container->lazy(Stub6::class, function () {
330+
$container->set(Stub6::class, $container->lazy(Stub6::class, function () {
331331
return new Stub6();
332-
});
332+
}));
333333

334334
$resource = $container->get(Stub6::class);
335335

@@ -350,10 +350,10 @@ public function testGetLazyProxyInstance()
350350
$factoryCalled = false;
351351

352352
$container = new Container();
353-
$container->lazy(Stub6::class, function () use (&$factoryCalled) {
353+
$container->set(Stub6::class, $container->lazy(Stub6::class, function () use (&$factoryCalled) {
354354
$factoryCalled = true;
355355
return new Stub6();
356-
});
356+
}));
357357

358358
$resource = $container->get(Stub6::class);
359359

src/Container.php

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -666,31 +666,27 @@ public function share($key, $value, $protected = false)
666666
}
667667

668668
/**
669-
* Create a lazy proxy resource for given class, and register it in the Container.
669+
* Create a lazy proxy factory for given class.
670670
*
671671
* @param string $class Full class name of the resource.
672672
* @param callable $factory Callback to create the class instance. The callback must return instance of the given class.
673-
* @param boolean $shared True to create and store a shared instance.
674-
* @param boolean $protected True to protect this item from being overwritten. Useful for services.
675673
*
676-
* @return $this
674+
* @return callable
677675
*
678676
* @since __DEPLOY_VERSION__
679677
*/
680-
final public function lazy(string $class, callable $factory, bool $shared = false, bool $protected = false): static
678+
final public function lazy(string $class, callable $factory): callable
681679
{
682680
if (PHP_VERSION_ID < 80400) {
683-
return $this->set($class, $factory, $shared, $protected);
681+
return $factory;
684682
}
685683

686684
// Create a Lazy Proxy factory
687-
$lazyFactory = function () use ($class, $factory) {
685+
return function () use ($class, $factory) {
688686
return (new \ReflectionClass($class))->newLazyProxy(function () use ($factory) {
689687
return $factory($this);
690688
});
691689
};
692-
693-
return $this->set($class, $lazyFactory, $shared, $protected);
694690
}
695691

696692
/**

0 commit comments

Comments
 (0)