-
Notifications
You must be signed in to change notification settings - Fork 2
/
Factory.php
54 lines (45 loc) · 1.3 KB
/
Factory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
declare(strict_types=1);
namespace Dhii\Services;
use Dhii\Services\Factories\Constructor;
use Psr\Container\ContainerInterface;
/**
* A simple implementation for a factory service.
*
* This implementation will automatically resolve any specified dependencies and pass them as arguments to the
* definition function. The container will NOT be included in the arguments.
*
* Example usage:
* ```
* new Factory(['foo', 'bar'], function($foo, $bar) {
* return new SomeClass($foo, $bar);
* });
* ```
*
* @see Constructor For a similar implementation that automatically injects dependencies into constructors.
* @see Extension For a similar implementation that can be used with extension services.
*/
class Factory extends Service
{
use ResolveKeysCapableTrait;
/** @var callable */
protected $definition;
/**
* @inheritDoc
*
* @param callable $definition The factory definition.
*/
public function __construct(array $dependencies, callable $definition)
{
parent::__construct($dependencies);
$this->definition = $definition;
}
/**
* @inheritDoc
*/
public function __invoke(ContainerInterface $c)
{
$deps = $this->resolveDeps($c, $this->dependencies);
return ($this->definition)(...$deps);
}
}