-
Notifications
You must be signed in to change notification settings - Fork 45
/
Proxy.php
53 lines (46 loc) · 1.21 KB
/
Proxy.php
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
47
48
49
50
51
52
53
<?php
/**
* Proxy design pattern (lazy loading)
*
* @author Enrico Zimuel ([email protected])
* @see http://en.wikipedia.org/wiki/Proxy_pattern
*/
interface ImageInterface
{
public function display();
}
class Image implements ImageInterface
{
protected $filename;
public function __construct($filename) {
$this->filename = $filename;
$this->loadFromDisk();
}
protected function loadFromDisk() {
echo "Loading {$this->filename}\n";
}
public function display() {
echo "Display {$this->filename}\n";
}
}
class ProxyImage implements ImageInterface
{
protected $id;
protected $image;
public function __construct($filename) {
$this->filename = $filename;
}
public function display() {
if (null === $this->image) {
$this->image = new Image($this->filename);
}
return $this->image->display();
}
}
// Usage example
$filename = 'test.png';
$image1 = new Image($filename); // loading necessary
echo $image1->display(); // loading unnecessary
$image2 = new ProxyImage($filename); // loading unnecessary
echo $image2->display(); // loading necessary
echo $image2->display(); // loading unnecessary