Skip to content

Commit a39b5e5

Browse files
committed
發布 1.0.0 版本。
0 parents  commit a39b5e5

File tree

5 files changed

+265
-0
lines changed

5 files changed

+265
-0
lines changed

.gitignore

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# 忽略 VSCode 的工作台設定檔案
2+
*.code-workspace
3+
4+
# 忽略 macOS 系統自動生成的 .DS_Store 檔案與資料夾圖標
5+
.DS_Store
6+
Icon?
7+
8+
# 忽略其他
9+
memo.md

LICENSE

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2025 邱敬幃 Pardn Chiu
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# PD\Cache
2+
3+
> PD\Cache is a hybrid caching system for PHP that combines Redis and filesystem caching with automatic fallback support. Provides seamless caching capabilities even when Redis is unavailable.
4+
5+
![tag](https://img.shields.io/badge/tag-PHP%20Library-bb4444)
6+
![size](https://img.shields.io/github/size/pardnchiu/PHP-Cache/src/SQL.php)<br>
7+
![version](https://img.shields.io/packagist/v/pardnchiu/cache)
8+
![download](https://img.shields.io/packagist/dm/pardnchiu/cache)
9+
10+
## Features
11+
12+
- Hybrid caching strategy (Redis + Filesystem)
13+
- Automatic fallback to filesystem when Redis is unavailable
14+
- Built-in content optimization for HTML/Text content
15+
- Automatic cache expiration handling
16+
- Cache cleanup mechanism
17+
- MD5 key generation for cache entries
18+
19+
## Key Capabilities
20+
21+
- Get/Set cache with automatic storage selection
22+
- Content minification for HTML/Text
23+
- Automatic cache expiration
24+
- Cache cleanup for expired entries
25+
- Fallback mechanism for system resilience
26+
27+
## Dependencies
28+
29+
- `pardnchiu/redis` - For Redis caching support (optional)
30+
- `/storage/caches` - Write permission on storage directory
31+
32+
## How to Use
33+
34+
### Install
35+
36+
```SHELL
37+
composer require pardnchiu/cache
38+
```
39+
40+
```PHP
41+
// Initialize cache with Redis support
42+
$redis = new PD\Redis();
43+
$cache = new PD\Cache($redis);
44+
45+
// Set cache with 1-hour expiration
46+
$cache->set("page-key", $content, 3600);
47+
48+
// Get cached content
49+
$content = $cache->get("page-key");
50+
51+
// Clean expired cache entries
52+
$cache->clean();
53+
54+
// Initialize cache without Redis (filesystem only)
55+
$cache = new PD\Cache();
56+
```
57+
58+
## License
59+
60+
This source code project is licensed under the [MIT](https://github.com/pardnchiu/PHP-Cache/blob/main/LICENSE) license.
61+
62+
## Creator
63+
64+
<img src="https://avatars.githubusercontent.com/u/25631760" align="left" width="96" height="96" style="margin-right: 0.5rem;">
65+
66+
<h4 style="padding-top: 0">邱敬幃 Pardn Chiu</h4>
67+
68+
<a href="mailto:dev@pardn.io" target="_blank">
69+
<img src="https://pardn.io/image/email.svg" width="48" height="48">
70+
</a> <a href="https://linkedin.com/in/pardnchiu" target="_blank">
71+
<img src="https://pardn.io/image/linkedin.svg" width="48" height="48">
72+
</a>
73+
74+
***
75+
76+
©️ 2024 [邱敬幃 Pardn Chiu](https://pardn.io)

composer.json

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
{
2+
"name": "pardnchiu/cache",
3+
"description": "PD\\Cache is A hybrid caching system for PHP that combines Redis and filesystem caching with automatic fallback support.",
4+
"type": "library",
5+
"license": "MIT",
6+
"authors": [
7+
{
8+
"name": "邱敬幃 Pardn Chiu",
9+
"email": "dev@pardn.io"
10+
}
11+
],
12+
"minimum-stability": "stable",
13+
"require": {
14+
"php": ">=8.0"
15+
},
16+
"suggest": {
17+
"pardnchiu/redis": "For Redis caching support"
18+
},
19+
"require-dev": {},
20+
"autoload": {
21+
"psr-4": {
22+
"PD\\": "src/"
23+
},
24+
"exclude-from-classmap": [
25+
".gitignore",
26+
"*.md",
27+
"composer.json"
28+
]
29+
},
30+
"autoload-dev": {
31+
"psr-4": {}
32+
},
33+
"scripts": {},
34+
"extra": {
35+
"branch-alias": {}
36+
},
37+
"config": {
38+
"sort-packages": true
39+
}
40+
}

src/Cache.php

+119
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
<?php
2+
3+
namespace PD;
4+
5+
class Cache
6+
{
7+
private $REDIS_CLIENT;
8+
9+
// 建構函式,初始化 Redis 客戶端
10+
public function __construct($REDIS_CLIENT = null)
11+
{
12+
$this->REDIS_CLIENT = $REDIS_CLIENT;
13+
}
14+
15+
// 取得快取資料
16+
public function get($page)
17+
{
18+
$page_key = md5($page); // 生成頁面鍵值
19+
20+
// 若 Redis 已連線,從 Redis 取得資料
21+
if ($this->REDIS_CLIENT->isConnected()) {
22+
return $this->REDIS_CLIENT->get(1, $page_key);
23+
};
24+
25+
// 設定快取檔案路徑
26+
$folder = get_path("/storage/caches");
27+
$file = $folder . "/" . $page_key . ".json";
28+
29+
// 資料夾不存在且無法創建時,返回 null
30+
if (!file_exists($folder) && !mkdir($folder, 0777, true)) {
31+
return null;
32+
};
33+
34+
// 資料夾不可寫入時,返回 null
35+
if (!is_writable($folder)) {
36+
return null;
37+
};
38+
39+
// 快取檔案不存在時,返回 null
40+
if (!file_exists($file)) {
41+
return null;
42+
};
43+
44+
$content = file_get_contents($file); // 讀取快取檔案內容
45+
$data = json_decode($content, true); // 解碼 JSON 快取內容
46+
47+
// 快取過期,刪除並返回 null
48+
if (isset($data["expire"]) && $data["expire"] < time()) {
49+
unlink($file);
50+
return null;
51+
};
52+
53+
return $data["content"]; // 返回快取內容
54+
}
55+
56+
// 設定快取資料
57+
public function set($page, $content, $expire)
58+
{
59+
$page_key = md5($page); // 生成頁面鍵值
60+
$content = preg_replace("/\n[ ]*/", "", $content); // 移除多餘空白與換行
61+
$content = preg_replace("/>[ ]*</", "><", $content); // 移除標籤間空白
62+
63+
// 若 Redis 已連線,將資料存入 Redis
64+
if ($this->REDIS_CLIENT->isConnected()) {
65+
$this->REDIS_CLIENT->set(1, $page_key, $content, $expire);
66+
return $content;
67+
};
68+
69+
// 設定快取檔案路徑
70+
$folder = get_path("/storage/caches");
71+
$file = $folder . "/" . $page_key . ".json";
72+
$data = [
73+
"content" => $content,
74+
"expire" => time() + $expire
75+
]; // 設定快取資料
76+
77+
// 資料夾不存在且無法創建時,返回 null
78+
if (!file_exists($folder) && !mkdir($folder, 0777, true)) {
79+
return null;
80+
}
81+
82+
// 資料夾不可寫入時,返回 null
83+
if (!is_writable($folder)) {
84+
return null;
85+
};
86+
87+
// 將快取資料寫入檔案
88+
file_put_contents($file, json_encode($data, JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
89+
90+
return $content; // 返回快取內容
91+
}
92+
93+
// 清理過期的快取資料
94+
public function clean()
95+
{
96+
$folder = get_path("/storage/caches");
97+
98+
// 若資料夾不存在,直接返回
99+
if (!file_exists($folder)) {
100+
return;
101+
};
102+
103+
$files = glob($folder . "/*.json"); // 獲取所有快取檔案
104+
105+
foreach ($files as $file) {
106+
if (!file_exists($file)) {
107+
continue;
108+
};
109+
110+
$content = file_get_contents($file); // 讀取快取檔案內容
111+
$data = json_decode($content, true); // 解碼 JSON 快取內容
112+
113+
// 若快取已過期,刪除快取檔案
114+
if (isset($data["expire"]) && $data["expire"] < time()) {
115+
unlink($file);
116+
};
117+
};
118+
}
119+
}

0 commit comments

Comments
 (0)