Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- One of the usecases where this is useful is a result object to avoid multiple return types.
- <?php
- interface PingResultInterface
- {
- public function isSuccessful();
- }
- ?>
- Given we have 2 implementations, one would be a ping that is executed before creating the object (value object) and one that's lazy (proxy), they could be made runtime based on certain things:
- <?php
- // Pinger implements PingerInterface
- public function ping(string $host) : PingResultInterface
- {
- return new class($this->ping($host)) implements PingResultInterface {
- private $result;
- public function __construct(bool $result)
- {
- $this->result = $result;
- }
- public function isSuccessful()
- {
- return $this->result;
- }
- }
- }
- <?php
- // LazyPinger implements PingerInterface
- // __construct(PingerInterface $pinger) decorator
- public function ping(string $host) : PingResultInterface
- {
- return new class($this, $host) implements PingResultInterface {
- private $pinger
- private $host;
- public function __construct(PingerInterface $pinger, string $host)
- {
- $this->pinger = $pinger;
- $this->host = $host;
- }
- public function isSuccessful()
- {
- // could add caching layer
- return $this->pinger->ping($this->host);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement