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