Advertisement
3xception

Pinger, anonymous class php

Oct 15th, 2015
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.39 KB | None | 0 0
  1. One of the usecases where this is useful is a result object to avoid multiple return types.
  2. <?php
  3. interface PingResultInterface
  4. {
  5.     public function isSuccessful();
  6. }
  7. ?>
  8.  
  9. 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:
  10.  
  11. <?php
  12. // Pinger implements PingerInterface
  13. public function ping(string $host) : PingResultInterface
  14. {
  15.     return new class($this->ping($host)) implements PingResultInterface {
  16.         private $result;
  17.  
  18.         public function __construct(bool $result)
  19.         {
  20.             $this->result = $result;
  21.         }
  22.  
  23.         public function isSuccessful()
  24.         {
  25.             return $this->result;
  26.         }
  27.     }
  28. }
  29.  
  30.  
  31. <?php
  32. // LazyPinger implements PingerInterface
  33. // __construct(PingerInterface $pinger) decorator
  34. public function ping(string $host) : PingResultInterface
  35. {
  36.     return new class($this, $host) implements PingResultInterface {
  37.         private $pinger
  38.         private $host;
  39.  
  40.         public function __construct(PingerInterface $pinger, string $host)
  41.         {
  42.             $this->pinger = $pinger;
  43.             $this->host   = $host;
  44.         }
  45.  
  46.         public function isSuccessful()
  47.         {
  48.             // could add caching layer
  49.             return $this->pinger->ping($this->host);
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement