Skip to content

Instantly share code, notes, and snippets.

@sokolovvs
Last active November 12, 2024 07:12
Show Gist options
  • Select an option

  • Save sokolovvs/c54e0190fb3205700bb5d06594e36d80 to your computer and use it in GitHub Desktop.

Select an option

Save sokolovvs/c54e0190fb3205700bb5d06594e36d80 to your computer and use it in GitHub Desktop.
Refactoring php
<?php
use Framework\HttpClient;
use Framework\Cache;
use Framework\Response;
use Framework\JsonResponse;
class CalendarController
{
public function actionshow() {
$calendar = new Calendar(new HttpClient());
$calendar->_cache = new Cache();
return new Response($calendar->getHolidays());
}
public function actionShowJson(): JsonResponse
{
$calendar = new Calendar(new HttpClient());
$calendar->_cache = new Cache();
return new JsonResponse(str_replace(['<pre>', '</pre>'], $calendar->getHolidays()));
}
}
class Calendar {
public $_cache;
public function __construct(HttpClient $client)
{
if (!$this->_cache || !$this->_cache->has('holidays')) {
try {
$this->hol = $client->request('http://calendar.google.com/...');
$this->_cache->set('holidays', $this->hol);
} catch (\Throwable $exception) {
$this->hol = [];
}
} else {
$this->hol= $this->_cache->get('holidays');
}
}
public function getHolidays (): string
{
return '<pre>'.json_encode($this->hol).'</pre>';
}
}
namespace Framework;
interface HttpClientResponse
{
public function getBody(): string;
public function getJsonBody(): array;
}
interface HttpClient
{
public function request(string $url): HttpClientResponse;
}
interface Cache
{
public function has(string $key): bool;
/**
* @param mixed $value
*/
public function set(string $key, $value): void;
/**
* @return mixed
*/
public function get(string $key);
}
interface Response
{
public function __construct(string $body);
}
interface JsonResponse
{
public function __construct(array $jsonBody);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment