大家好!
您的應用程式是否因為重複的資料庫查詢而運行緩慢?或是在不同的快取庫之間切換時遇到困難?讓我們深入探討 PSR-6,這個標準讓 PHP 中的快取變得可預測且可互換!
本文是 PHP PSR 標準系列的一部分。如果您是新手,不妨從 PSR-1 基礎開始。
在 PSR-6 之前,每個快取庫都有自己獨特的工作方式。想要從 Memcached 切換到 Redis?重寫您的程式碼。從一個框架遷移到另一個框架?學習新的快取 API。 PSR-6 透過提供所有快取庫都可以實現的通用介面來解決這個問題。
讓我們來看看兩個主要參與者:
CacheItemPoolInterface
這是您的快取管理器。可以將其視為一個倉庫,您可以在其中儲存和檢索項目:
<code class="language-php"><?php namespace Psr\Cache; interface CacheItemPoolInterface { public function getItem($key); public function getItems(array $keys = array()); public function hasItem($key); public function clear(); public function deleteItem($key); public function deleteItems(array $keys); public function save(CacheItemInterface $item); public function saveDeferred(CacheItemInterface $item); public function commit(); } ?></code>
CacheItemInterface
這表示快取中的單一項目:
<code class="language-php"><?php namespace Psr\Cache; interface CacheItemInterface { public function getKey(); public function get(); public function isHit(); public function set($value); public function expiresAt($expiration); public function expiresAfter($time); } ?></code>
以下是我們程式碼庫中的一個實際範例:
<code class="language-php"><?php namespace JonesRussell\PhpFigGuide\PSR6; use Psr\Cache\CacheItemInterface; use DateTimeInterface; use DateInterval; use DateTime; class CacheItem implements CacheItemInterface { private $key; private $value; private $isHit; private $expiration; public function __construct(string $key) { $this->key = $key; $this->isHit = false; } public function getKey(): string { return $this->key; } public function get() { return $this->value; } public function isHit(): bool { return $this->isHit; } public function set($value): self { $this->value = $value; return $this; } public function expiresAt(?DateTimeInterface $expiration): self { $this->expiration = $expiration; return $this; } public function expiresAfter($time): self { if ($time instanceof DateInterval) { $this->expiration = (new DateTime())->add($time); } elseif (is_int($time)) { $this->expiration = (new DateTime())->add(new DateInterval("PT{$time}S")); } else { $this->expiration = null; } return $this; } // Helper method for our implementation public function getExpiration(): ?DateTimeInterface { return $this->expiration; } // Helper method for our implementation public function setIsHit(bool $hit): void { $this->isHit = $hit; } }</code>
<code class="language-php"><?php namespace JonesRussell\PhpFigGuide\PSR6; use Psr\Cache\CacheItemPoolInterface; use Psr\Cache\CacheItemInterface; use RuntimeException; class FileCachePool implements CacheItemPoolInterface { private $directory; private $deferred = []; public function __construct(string $directory) { if (!is_dir($directory) && !mkdir($directory, 0777, true)) { throw new RuntimeException("Cannot create cache directory: {$directory}"); } $this->directory = $directory; } public function getItem($key): CacheItemInterface { $this->validateKey($key); if (isset($this->deferred[$key])) { return $this->deferred[$key]; } $item = new CacheItem($key); $path = $this->getPath($key); if (file_exists($path)) { try { $data = unserialize(file_get_contents($path)); if (!$data['expiration'] || $data['expiration'] > new DateTime()) { $item->set($data['value']); $item->setIsHit(true); return $item; } unlink($path); } catch (\Exception $e) { // Log error and continue with cache miss } } return $item; } public function getItems(array $keys = []): iterable { $items = []; foreach ($keys as $key) { $items[$key] = $this->getItem($key); } return $items; } public function hasItem($key): bool { return $this->getItem($key)->isHit(); } public function clear(): bool { $this->deferred = []; $files = glob($this->directory . '/*.cache'); if ($files === false) { return false; } $success = true; foreach ($files as $file) { if (!unlink($file)) { $success = false; } } return $success; } public function deleteItem($key): bool { $this->validateKey($key); unset($this->deferred[$key]); $path = $this->getPath($key); if (file_exists($path)) { return unlink($path); } return true; } public function deleteItems(array $keys): bool { $success = true; foreach ($keys as $key) { if (!$this->deleteItem($key)) { $success = false; } } return $success; } public function save(CacheItemInterface $item): bool { $path = $this->getPath($item->getKey()); $data = [ 'value' => $item->get(), 'expiration' => $item->getExpiration() ]; try { if (file_put_contents($path, serialize($data)) === false) { return false; } return true; } catch (\Exception $e) { return false; } } public function saveDeferred(CacheItemInterface $item): bool { $this->deferred[$item->getKey()] = $item; return true; } public function commit(): bool { $success = true; foreach ($this->deferred as $item) { if (!$this->save($item)) { $success = false; } } $this->deferred = []; return $success; } private function getPath(string $key): string { return $this->directory . '/' . sha1($key) . '.cache'; } private function validateKey(string $key): void { if (!is_string($key) || preg_match('#[{}()/@:\\]#', $key)) { throw new InvalidArgumentException( 'Invalid key: ' . var_export($key, true) ); } } }</code>
讓我們看看如何在實際程式碼中使用它:
<code class="language-php">// 基本用法 $pool = new FileCachePool('/path/to/cache'); try { // 存储值 $item = $pool->getItem('user.1'); if (!$item->isHit()) { $userData = $database->fetchUser(1); // 您的数据库调用 $item->set($userData) ->expiresAfter(3600); // 1 小时 $pool->save($item); } $user = $item->get(); } catch (\Exception $e) { // 优雅地处理错误 log_error('缓存操作失败:' . $e->getMessage()); $user = $database->fetchUser(1); // 回退到数据库 }</code>
明天,我們將討論 PSR-7(HTTP 訊息介面)。如果您對更簡單的快取感興趣,請繼續關注我們即將推出的 PSR-16(簡單快取)文章,該文章提供了比 PSR-6 更直接的替代方案。
以上是PHP 中的 PSR 快取接口的詳細內容。更多資訊請關注PHP中文網其他相關文章!