Skip to content

Commit be1be3a

Browse files
author
Dominik Liebler
committed
introduced Service interface to ServiceLocator
1 parent 92482c2 commit be1be3a

File tree

4 files changed

+17
-36
lines changed

4 files changed

+17
-36
lines changed

More/ServiceLocator/LogService.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace DesignPatterns\More\ServiceLocator;
44

5-
class LogService
5+
class LogService implements Service
66
{
7+
78
}

More/ServiceLocator/Service.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?php
2+
3+
namespace DesignPatterns\More\ServiceLocator;
4+
5+
interface Service
6+
{
7+
8+
}

More/ServiceLocator/ServiceLocator.php

Lines changed: 7 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -5,60 +5,34 @@
55
class ServiceLocator
66
{
77
/**
8-
* @var array
8+
* @var array|Service[]
99
*/
1010
private $services = [];
1111

1212
/**
13-
* @var array
13+
* @var array|Service[]
1414
*/
1515
private $instantiated = [];
1616

17-
/**
18-
* @var array
19-
*/
20-
private $shared = [];
21-
22-
/**
23-
* instead of supplying a class here, you could also store a service for an interface
24-
*
25-
* @param string $class
26-
* @param object $service
27-
* @param bool $share
28-
*/
29-
public function addInstance(string $class, $service, bool $share = true)
17+
public function addInstance(string $class, Service $service)
3018
{
3119
$this->services[$class] = $service;
3220
$this->instantiated[$class] = $service;
33-
$this->shared[$class] = $share;
3421
}
3522

36-
/**
37-
* instead of supplying a class here, you could also store a service for an interface
38-
*
39-
* @param string $class
40-
* @param array $params
41-
* @param bool $share
42-
*/
43-
public function addClass(string $class, array $params, bool $share = true)
23+
public function addClass(string $class, array $params)
4424
{
4525
$this->services[$class] = $params;
46-
$this->shared[$class] = $share;
4726
}
4827

4928
public function has(string $interface): bool
5029
{
5130
return isset($this->services[$interface]) || isset($this->instantiated[$interface]);
5231
}
5332

54-
/**
55-
* @param string $class
56-
*
57-
* @return object
58-
*/
59-
public function get(string $class)
33+
public function get(string $class): Service
6034
{
61-
if (isset($this->instantiated[$class]) && $this->shared[$class]) {
35+
if (isset($this->instantiated[$class])) {
6236
return $this->instantiated[$class];
6337
}
6438

@@ -81,9 +55,7 @@ public function get(string $class)
8155
throw new \OutOfRangeException('Too many arguments given');
8256
}
8357

84-
if ($this->shared[$class]) {
85-
$this->instantiated[$class] = $object;
86-
}
58+
$this->instantiated[$class] = $object;
8759

8860
return $object;
8961
}

More/ServiceLocator/uml/uml.png

16 KB
Loading

0 commit comments

Comments
 (0)