大家好!
您的應用程式是否因為重複的資料庫查詢而運行緩慢?或是在不同的快取庫之間切換時遇到困難?讓我們深入探討 PSR-6,這個標準讓 PHP 中的快取變得可預測且可互換!
本文是 PHP PSR 標準系列的一部分。如果您是新手,不妨從 PSR-1 基礎開始。
PSR-6 解決什麼問題? (2 分鐘)
在 PSR-6 之前,每個快取庫都有自己獨特的工作方式。想要從 Memcached 切換到 Redis?重寫您的程式碼。從一個框架遷移到另一個框架?學習新的快取 API。 PSR-6 透過提供所有快取庫都可以實現的通用介面來解決這個問題。
核心介面(5 分鐘)
讓我們來看看兩個主要參與者:
1. CacheItemPoolInterface
這是您的快取管理器。可以將其視為一個倉庫,您可以在其中儲存和檢索項目:
<?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(); } ?>
2. CacheItemInterface
這表示快取中的單一項目:
<?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); } ?>
實際應用(10 分鐘)
以下是我們程式碼庫中的一個實際範例:
1. 快取項目實作
<?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; } }
2. 快取池實作
<?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) ); } } }
實際使用(5 分鐘)
讓我們看看如何在實際程式碼中使用它:
// 基本用法 $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); // 回退到数据库 }
常見陷阱(3 分鐘)
- 鍵驗證
- 錯誤處理
下一步是什麼?
明天,我們將討論 PSR-7(HTTP 訊息介面)。如果您對更簡單的快取感興趣,請繼續關注我們即將推出的 PSR-16(簡單快取)文章,該文章提供了比 PSR-6 更直接的替代方案。
資源
- 官方 PSR-6 規範
- 我們的範例程式碼庫 (v0.6.0 - PSR-6 實作)
- Symfony 快取元件
- PHP 快取
以上是PHP 中的 PSR 快取接口的詳細內容。更多資訊請關注PHP中文網其他相關文章!

要保護應用免受與會話相關的XSS攻擊,需採取以下措施:1.設置HttpOnly和Secure標誌保護會話cookie。 2.對所有用戶輸入進行輸出編碼。 3.實施內容安全策略(CSP)限制腳本來源。通過這些策略,可以有效防護會話相關的XSS攻擊,確保用戶數據安全。

优化PHP会话性能的方法包括:1.延迟会话启动,2.使用数据库存储会话,3.压缩会话数据,4.管理会话生命周期,5.实现会话共享。这些策略能显著提升应用在高并发环境下的效率。

theSession.gc_maxlifetimesettinginphpdeterminesthelifespanofsessiondata,setInSeconds.1)它'sconfiguredinphp.iniorviaini_set().2)abalanceisesneededeededeedeedeededto toavoidperformance andunununununexpectedLogOgouts.3)

在PHP中,可以使用session_name()函數配置會話名稱。具體步驟如下:1.使用session_name()函數設置會話名稱,例如session_name("my_session")。 2.在設置會話名稱後,調用session_start()啟動會話。配置會話名稱可以避免多應用間的會話數據衝突,並增強安全性,但需注意會話名稱的唯一性、安全性、長度和設置時機。

會話ID應在登錄時、敏感操作前和每30分鐘定期重新生成。 1.登錄時重新生成會話ID可防會話固定攻擊。 2.敏感操作前重新生成提高安全性。 3.定期重新生成降低長期利用風險,但需權衡用戶體驗。

在PHP中設置會話cookie參數可以通過session_set_cookie_params()函數實現。 1)使用該函數設置參數,如過期時間、路徑、域名、安全標誌等;2)調用session_start()使參數生效;3)根據需求動態調整參數,如用戶登錄狀態;4)注意設置secure和httponly標誌以提升安全性。

在PHP中使用會話的主要目的是維護用戶在不同頁面之間的狀態。 1)會話通過session_start()函數啟動,創建唯一會話ID並存儲在用戶cookie中。 2)會話數據保存在服務器上,允許在不同請求間傳遞數據,如登錄狀態和購物車內容。

如何在子域名間共享會話?通過設置通用域名的會話cookie實現。 1.在服務器端設置會話cookie的域為.example.com。 2.選擇合適的會話存儲方式,如內存、數據庫或分佈式緩存。 3.通過cookie傳遞會話ID,服務器根據ID檢索和更新會話數據。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

Dreamweaver Mac版
視覺化網頁開發工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

WebStorm Mac版
好用的JavaScript開發工具