Created
April 13, 2024 09:35
-
-
Save atakde/300be4e2ea2785e03108cc9b11f6c254 to your computer and use it in GitHub Desktop.
Proxy Pattern Example in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
interface ImageInterface | |
{ | |
public function display(); | |
} | |
class Image implements ImageInterface | |
{ | |
public function __construct( | |
private string $imageName | |
) { | |
$this->loadImage(); | |
} | |
private function loadImage() | |
{ | |
echo "Loading image " . $this->imageName . PHP_EOL; | |
} | |
public function display() | |
{ | |
echo "Display " . $this->imageName . PHP_EOL; | |
} | |
} | |
class ProxyImage implements ImageInterface | |
{ | |
private $image; | |
public function __construct( | |
private string $imageName | |
) { | |
} | |
public function display() | |
{ | |
if (!$this->image) { | |
$this->image = new Image($this->imageName); | |
} | |
$this->image->display(); | |
} | |
} | |
// Just one time loading the image in this example. | |
$proxyImage = new ProxyImage("image.png"); | |
$proxyImage->display(); | |
$proxyImage->display(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment