Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Example;
- use Doctrine\Common\Cache\Cache;
- use GuzzleHttp\Client;
- use Symfony\Component\Filesystem\Filesystem;
- interface Fetcher
- {
- public function fetch(string $url): string;
- }
- class HttpFetcher implements Fetcher
- {
- /**
- * @var Client
- */
- private $httpClient;
- public function fetch(string $url): string
- {
- return $this->httpClient->get($url);
- }
- }
- abstract class DecoratorFetcher implements Fetcher
- {
- /**
- * @var Fetcher
- */
- protected $next;
- public function __construct(Fetcher $next)
- {
- $this->next = $next;
- }
- }
- class CachingFetcher extends DecoratorFetcher
- {
- private const CACHE_ID = 'cycki';
- /**
- * @var Cache
- */
- private $cache;
- public function __construct(Fetcher $next, Cache $cache)
- {
- parent::__construct($next);
- $this->cache = $cache;
- }
- public function fetch(string $url): string
- {
- if ($this->cache->contains(self::CACHE_ID)) {
- return $this->cache->fetch(self::CACHE_ID);
- }
- $content = $this->fetch($url);
- $this->cache->save(self::CACHE_ID, $content);
- return $content;
- }
- }
- class CreatingBackupFetcher extends DecoratorFetcher
- {
- private const FILE = 'some/path.txt';
- /**
- * @var Filesystem
- */
- private $filesystem;
- public function __construct(Fetcher $next, Filesystem $filesystem)
- {
- parent::__construct($next);
- $this->filesystem = $filesystem;
- }
- public function fetch(string $url): string
- {
- $content = $this->next->fetch($url);
- $this->filesystem->remove(self::FILE);
- $this->filesystem->touch(self::FILE);
- $this->filesystem->appendToFile(self::FILE, $content);
- return $content;
- }
- }
Add Comment
Please, Sign In to add comment