|
1
|
|
|
<?php |
|
|
|
|
|
|
2
|
|
|
namespace CloudFrameworkTest\Patterns; |
|
3
|
|
|
require_once __DIR__ . '/../../src/autoload.php'; |
|
4
|
|
|
|
|
5
|
|
|
class SingletonTest extends \PHPUnit_Framework_TestCase |
|
6
|
|
|
{ |
|
7
|
|
|
/** |
|
8
|
|
|
* Test creation of instance |
|
9
|
|
|
* |
|
10
|
|
|
* @param string $instanceClass |
|
11
|
|
|
* |
|
12
|
|
|
* @return \CloudFramework\Patterns\Singleton |
|
13
|
|
|
*/ |
|
14
|
|
|
public function testInstanceCreation($instanceClass = '\CloudFramework\CloudFrameworkApp') |
|
15
|
|
|
{ |
|
16
|
|
|
/** @var \CloudFramework\Patterns\Singleton $instanceClass */ |
|
17
|
|
|
/** @var \CloudFramework\Patterns\Singleton $instance */ |
|
18
|
|
|
$instance = NULL; |
|
19
|
|
|
try { |
|
20
|
|
|
$instance = $instanceClass::getInstance(); |
|
21
|
|
|
$this->assertNotNull($instance, 'Create an instance of ' . $instanceClass); |
|
22
|
|
|
$this->assertInstanceOf('\CloudFramework\Patterns\Singleton', $instance, 'CloudFramework have to extend of Singleton'); |
|
23
|
|
|
$this->assertInstanceOf($instanceClass, $instance, 'Created object must be as creation definition class'); |
|
24
|
|
|
} catch (\Exception $e) { |
|
25
|
|
|
$this->fail('Can not create ' . $instanceClass . ' instance: ' . $e->getMessage()); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
return $instance; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* Test singleton instance |
|
33
|
|
|
* |
|
34
|
|
|
* @param string $instanceClass |
|
35
|
|
|
* |
|
36
|
|
|
* @return boolean |
|
37
|
|
|
*/ |
|
38
|
|
|
public function checkSingletonInstance($instanceClass = '\CloudFramework\CloudFrameworkApp') |
|
39
|
|
|
{ |
|
40
|
|
|
$instance1 = $this->testInstanceCreation($instanceClass); |
|
41
|
|
|
$instance2 = $this->testInstanceCreation($instanceClass); |
|
42
|
|
|
$this->assertNotNull($instance1); |
|
43
|
|
|
$instance1->app_name = 'myName'; |
|
|
|
|
|
|
44
|
|
|
$this->assertNotNull($instance2); |
|
45
|
|
|
$this->assertEquals($instance1, $instance2); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
} |
|
49
|
|
|
|
The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.
The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.
To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.