Skip to content

Commit

Permalink
Added Container::getFactory() method
Browse files Browse the repository at this point in the history
  • Loading branch information
guiwoda committed Sep 13, 2016
1 parent 40438b3 commit 99b5d92
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Illuminate/Container/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
};
}
}
44 changes: 44 additions & 0 deletions tests/Container/ContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 99b5d92

Please sign in to comment.