Skip to content

Commit

Permalink
Merge pull request #12 from michael-rubel/feat/remember
Browse files Browse the repository at this point in the history
Add `remember` method
  • Loading branch information
michael-rubel authored Nov 16, 2022
2 parents 1e3903b + c30762f commit 5db1e87
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Overrides/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,25 @@ public function makeOr($abstract, $parameters = [], Closure $callback = null)
}
}

/**
* Bind the given type to the container with the results of the callback.
*
* @param string $abstract
* @param \Closure|null $callback
* @param string $type
* @return mixed
*/
public function remember($abstract, Closure $callback = null, $type = 'scoped')
{
return $this->makeOr($abstract, function () use ($abstract, $callback, $type) {
$result = $callback($this);

$this->{$type}($abstract, fn () => $result);

return $result;
});
}

/**
* {@inheritdoc}
*
Expand Down
18 changes: 18 additions & 0 deletions tests/ContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -726,6 +726,24 @@ public function testMakeOrThrowsExceptionWhenCannotResolveAbstractOrExecuteCallb
$container = new Container;
$container->makeOr(ContainerInjectVariableStub::class);
}

public function testRemember()
{
$container = new Container;
$callback = function ($app) {
$app->bind('executed', fn () => 'once');

return true;
};

$var1 = $container->remember('test', $callback);
$this->assertTrue($var1);

$var2 = $container->remember('test', $callback);
$this->assertTrue($var2);

$this->assertSame('once', $container->make('executed'));
}
}

class CircularAStub
Expand Down

0 comments on commit 5db1e87

Please sign in to comment.