1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of the Scrawler package. |
4
|
|
|
* |
5
|
|
|
* (c) Pranjal Pandey <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace Scrawler\Traits; |
12
|
|
|
|
13
|
|
|
trait Container |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* Register a new service in the container, set force to true to override existing service. |
17
|
|
|
*/ |
18
|
|
|
public function register(string $name, mixed $value, bool $force = false): void |
19
|
|
|
{ |
20
|
|
|
if ($this->container->has($name) && !$force) { |
21
|
|
|
throw new \Scrawler\Exception\ContainerException('Service with this name already registered, please set $force = true to override'); |
22
|
|
|
} |
23
|
|
|
if ($this->container->has($name) && ('config' === $name || 'pipeline' === $name)) { |
24
|
|
|
throw new \Scrawler\Exception\ContainerException('Service with this name cannot be overridden'); |
25
|
|
|
} |
26
|
|
|
$this->container->set($name, $value); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Create a new definition helper. |
31
|
|
|
*/ |
32
|
|
|
public function create(string $class): \DI\Definition\Helper\CreateDefinitionHelper |
33
|
|
|
{ |
34
|
|
|
return \DI\create($class); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Make a new instance of class rather than getting same instance |
39
|
|
|
* use it before registering the class to container |
40
|
|
|
* app()->register('MyClass',app()->make('App\Class'));. |
41
|
|
|
* |
42
|
|
|
* @param array<mixed> $params |
43
|
|
|
*/ |
44
|
|
|
public function make(string $class, array $params = []): mixed |
45
|
|
|
{ |
46
|
|
|
return $this->container->make($class, $params); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Check if a class is registered in the container. |
51
|
|
|
*/ |
52
|
|
|
public function has(string $class): bool |
53
|
|
|
{ |
54
|
|
|
return $this->container->has($class); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Call given function , missing params will be resolved from container. |
59
|
|
|
* |
60
|
|
|
* @param array<mixed> $params |
61
|
|
|
*/ |
62
|
|
|
public function call(string|callable $class, array $params = []): mixed |
63
|
|
|
{ |
64
|
|
|
return $this->container->call($class, $params); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|