diff --git a/src/Illuminate/Container/Container.php b/src/Illuminate/Container/Container.php index de1fc790cca7..ea5a34976417 100755 --- a/src/Illuminate/Container/Container.php +++ b/src/Illuminate/Container/Container.php @@ -1238,4 +1238,21 @@ public function __set($key, $value) { $this[$key] = $value; } + + /** + * Get a closure to resolve the given type from the container. + * The given closure will have an optional [array $parameters] parameter + * to merge with the default parameters given when the factory was made. + * + * @param string $abstract + * @param array $defaults + * + * @return \Closure + */ + public function getFactory($abstract, array $defaults = []) + { + return function (array $params = []) use ($abstract, $defaults) { + return $this->make($abstract, $params + $defaults); + }; + } } diff --git a/tests/Container/ContainerTest.php b/tests/Container/ContainerTest.php index 7a90d3ed095e..ba16a1139f78 100755 --- a/tests/Container/ContainerTest.php +++ b/tests/Container/ContainerTest.php @@ -667,6 +667,50 @@ public function testContainerCanInjectSimpleVariable() $instance = $container->make('ContainerInjectVariableStub'); $this->assertInstanceOf('ContainerConcreteStub', $instance->something); } + + public function testContainerGetFactory() + { + $container = new Container; + $container->bind('name', function () { + return 'Taylor'; + }); + + $factory = $container->getFactory('name'); + $this->assertEquals($container->make('name'), $factory()); + } + + public function testContainerGetFactoryWithDefaultParams() + { + $container = new Container; + $container->bind('foo', function ($c, $parameters) { + return $parameters; + }); + + $factory = $container->getFactory('foo', [1, 2, 3]); + $this->assertEquals([1, 2, 3], $factory()); + } + + public function testContainerGetFactoryWithOverridenParams() + { + $container = new Container; + $container->bind('foo', function ($c, $parameters) { + return $parameters; + }); + + $factory = $container->getFactory('foo', [1, 2, 3]); + $this->assertEquals([4, 2, 3], $factory([4])); + } + + public function testContainerGetFactoryWithOverridenNamedParams() + { + $container = new Container; + $container->bind('foo', function ($c, $parameters) { + return $parameters; + }); + + $factory = $container->getFactory('foo', ['bar' => 1, 'baz' => 2]); + $this->assertEquals(['bar' => 1, 'baz' => 3], $factory(['baz' => 3])); + } } class ContainerConcreteStub