1 | <?php |
||
16 | class ServiceLocator |
||
17 | { |
||
18 | /** |
||
19 | * method to register a service |
||
20 | * |
||
21 | * @param string $serviceKey the key for the service |
||
22 | * @param mixed $object |
||
23 | * |
||
24 | * @throws ServiceLocatorException |
||
25 | */ |
||
26 | 26 | public static function registerService($serviceKey, $object) |
|
30 | |||
31 | /** |
||
32 | * checks if a service is registered |
||
33 | * |
||
34 | * @param string $serviceKey |
||
35 | * |
||
36 | * @return bool |
||
37 | */ |
||
38 | 31 | public static function hasService($serviceKey) |
|
42 | |||
43 | /** |
||
44 | * returns a service |
||
45 | * |
||
46 | * @param string $serviceKey the service key |
||
47 | * |
||
48 | * @return mixed |
||
49 | * @throws ServiceLocatorException |
||
50 | */ |
||
51 | 29 | public static function getService($serviceKey) |
|
55 | } |
||
56 |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: