Newer
Older
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
<?php
use DependencyInjector\DI;
require_once __DIR__ . '/MySingleton.php';
/**
* It's just a simple function that is using MySingleton static method.
*
* @return string
*/
function getTheSingletonResult() {
// before it was untestable
// $singleton = MySingleton::getInstance();
/** @var $singleton MySingleton */
$singleton = (DI::get(MySingleton::class))::getInstance();
return $singleton->getResult();
}
/**
* Class SingletonUser
*
* Uses the singleton to get a result.
*/
class SingletonUser {
/**
* This method shows a second way how to rewrite existing code to be testable. But remember that you have to
* set up the dependency before using it (for example in bootstrap).
*
* Example:
* DI::set('mySingleton', function() { return MySingleton::getInstance(); });
*
* @return mixed
*/
public function getResult() {
// before it was untestable
// return MySingleton::getInstance()->getResult();
return DI::get('mySingleton')->getResult();
}
}