Kotchasan Framework Documentation
CacheFactory - Cache Factory Pattern
CacheFactory - Cache Factory Pattern
ภาพรวม
CacheFactory เป็นคลาสที่ใช้ Factory Pattern สำหรับสร้าง Cache instances ต่างๆ ช่วยให้การจัดการและสร้าง Cache objects เป็นไปอย่างสะดวกและสม่ำเสมอ
Propertiesหลัก
- Factory Pattern: สร้าง Cache instances แบบ centralized
- Multiple Drivers: รองรับ Cache drivers หลายประเภท
- Configuration Management: จัดการ configuration สำหรับแต่ละ driver
- Singleton Support: รองรับ Singleton pattern สำหรับ Cache instances
- Type Safety: ตรวจสอบประเภท Cache driver ที่รองรับ
Usage CacheFactory
การสร้าง Cache Instances
use Kotchasan\Cache\CacheFactory;
// File Cache
$fileCache = CacheFactory::create('file', [
'cache_dir' => '/var/cache/myapp'
]);
// Memory Cache
$memoryCache = CacheFactory::create('memory');
// Redis Cache
$redisCache = CacheFactory::create('redis', [
'host' => 'localhost',
'port' => 6379,
'password' => 'secret',
'database' => 0
]);Usageกับ Configuration Files
// config/cache.php
return [
'default' => 'file',
'stores' => [
'file' => [
'driver' => 'file',
'cache_dir' => '/var/cache/app',
'default_ttl' => 3600
],
'redis' => [
'driver' => 'redis',
'host' => env('REDIS_HOST', 'localhost'),
'port' => env('REDIS_PORT', 6379),
'password' => env('REDIS_PASSWORD'),
'database' => 0
],
'memory' => [
'driver' => 'memory'
]
]
];
// Usage
$config = include 'config/cache.php';
$cache = CacheFactory::create(
$config['stores']['redis']['driver'],
$config['stores']['redis']
);Exampleการสร้าง Cache Manager
class CacheManager {
private static $instances = [];
public static function getInstance($store = 'default') {
if (!isset(self::$instances[$store])) {
$config = self::getConfig($store);
self::$instances[$store] = CacheFactory::create(
$config['driver'],
$config
);
}
return self::$instances[$store];
}
private static function getConfig($store) {
$configs = [
'default' => [
'driver' => 'file',
'cache_dir' => '/tmp/cache'
],
'session' => [
'driver' => 'redis',
'host' => 'localhost',
'port' => 6379,
'database' => 1
],
'query' => [
'driver' => 'file',
'cache_dir' => '/var/cache/queries'
]
];
return $configs[$store] ?? $configs['default'];
}
}
// Usage
$defaultCache = CacheManager::getInstance();
$sessionCache = CacheManager::getInstance('session');
$queryCache = CacheManager::getInstance('query');Methodsหลักของ CacheFactory
create(string $driver, array $config = [])
สร้าง Cache instance ตาม driver ที่กำหนด
// File Cache
$fileCache = CacheFactory::create('file', [
'cache_dir' => '/var/cache'
]);
// Redis Cache
$redisCache = CacheFactory::create('redis', [
'host' => '127.0.0.1',
'port' => 6379
]);
// Memory Cache
$memoryCache = CacheFactory::create('memory');Supported Drivers
1. File Driver
$fileCache = CacheFactory::create('file', [
'cache_dir' => '/path/to/cache', // required
'default_ttl' => 3600, // optional
'file_permission' => 0644 // optional
]);2. Memory Driver
$memoryCache = CacheFactory::create('memory', [
'default_ttl' => 300 // optional
]);3. Redis Driver
$redisCache = CacheFactory::create('redis', [
'host' => 'localhost', // required
'port' => 6379, // optional, default: 6379
'password' => null, // optional
'database' => 0, // optional, default: 0
'timeout' => 5.0, // optional, default: 5.0
'read_timeout' => 0, // optional
'persistent' => false, // optional
'prefix' => 'cache:' // optional
]);ExampleUsageในโปรเจกต์จริง
1. Multi-Environment Configuration
class AppCacheFactory {
public static function createForEnvironment($env = null) {
$env = $env ?: ($_ENV['APP_ENV'] ?? 'production');
switch ($env) {
case 'development':
return CacheFactory::create('memory');
case 'testing':
return CacheFactory::create('file', [
'cache_dir' => '/tmp/test_cache'
]);
case 'staging':
case 'production':
return CacheFactory::create('redis', [
'host' => $_ENV['REDIS_HOST'] ?? 'localhost',
'port' => $_ENV['REDIS_PORT'] ?? 6379,
'password' => $_ENV['REDIS_PASSWORD'] ?? null,
'database' => $env === 'staging' ? 1 : 0
]);
default:
throw new InvalidArgumentException("Unknown environment: {$env}");
}
}
}
// Usage
$cache = AppCacheFactory::createForEnvironment();2. Feature-Specific Cache
class FeatureCacheFactory {
public static function createUserCache() {
return CacheFactory::create('redis', [
'host' => 'redis-users.internal',
'database' => 0,
'prefix' => 'users:'
]);
}
public static function createSessionCache() {
return CacheFactory::create('redis', [
'host' => 'redis-sessions.internal',
'database' => 1,
'prefix' => 'sessions:'
]);
}
public static function createQueryCache() {
return CacheFactory::create('file', [
'cache_dir' => '/var/cache/queries',
'default_ttl' => 1800 // 30 minutes
]);
}
public static function createPageCache() {
return CacheFactory::create('file', [
'cache_dir' => '/var/cache/pages',
'default_ttl' => 3600 // 1 hour
]);
}
}
// Usage
$userCache = FeatureCacheFactory::createUserCache();
$sessionCache = FeatureCacheFactory::createSessionCache();
$queryCache = FeatureCacheFactory::createQueryCache();
$pageCache = FeatureCacheFactory::createPageCache();3. Performance Testing และ Fallback
class ReliableCacheFactory {
public static function createWithFallback() {
try {
// พยายามใช้ Redis ก่อน
$redisCache = CacheFactory::create('redis', [
'host' => 'localhost',
'port' => 6379,
'timeout' => 2.0
]);
// ทดสอบการเชื่อมต่อ
$redisCache->set('test_connection', true, 5);
if ($redisCache->get('test_connection')) {
$redisCache->delete('test_connection');
return $redisCache;
}
} catch (Exception $e) {
error_log("Redis cache failed, falling back to file cache: " . $e->getMessage());
}
// Fallback เป็น File Cache
return CacheFactory::create('file', [
'cache_dir' => '/var/cache/fallback'
]);
}
public static function createPerformanceOptimized() {
$memoryLimit = ini_get('memory_limit');
$memoryInBytes = self::parseMemoryLimit($memoryLimit);
// ถ้า memory เยอะพอ ใช้ Memory Cache
if ($memoryInBytes > 128 1024 1024) { // > 128MB
return CacheFactory::create('memory');
}
// ถ้าไม่ ใช้ File Cache
return CacheFactory::create('file', [
'cache_dir' => '/var/cache/performance'
]);
}
private static function parseMemoryLimit($limit) {
$limit = trim($limit);
$last = strtolower($limit[strlen($limit)-1]);
$value = (int) $limit;
switch($last) {
$value = 102; // 4;
$value = 102; // 4;
case 'k': $value *= 1024;
}
return $value;
}
}4. Cache Pool Management
class CachePoolManager {
private $pools = [];
public function addPool($name, $driver, $config) {
$this->pools[$name] = [
'driver' => $driver,
'config' => $config,
'instance' => null
];
return $this;
}
public function getPool($name) {
if (!isset($this->pools[$name])) {
throw new InvalidArgumentException("Cache pool '{$name}' not found");
}
$pool = &$this->pools[$name];
if ($pool['instance'] === null) {
$pool['instance'] = CacheFactory::create(
$pool['driver'],
$pool['config']
);
}
return $pool['instance'];
}
public function clearAll() {
foreach ($this->pools as $pool) {
if ($pool['instance'] !== null) {
$pool['instance']->clear();
}
}
}
}
// การตั้งค่า
$poolManager = new CachePoolManager();
$poolManager
->addPool('users', 'redis', ['host' => 'redis-1', 'database' => 0])
->addPool('sessions', 'redis', ['host' => 'redis-2', 'database' => 0])
->addPool('queries', 'file', ['cache_dir' => '/var/cache/sql'])
->addPool('pages', 'file', ['cache_dir' => '/var/cache/html']);
// Usage
$userCache = $poolManager->getPool('users');
$sessionCache = $poolManager->getPool('sessions');
$queryCache = $poolManager->getPool('queries');Best Practices
1. การใช้ Environment Variables
// การตั้งค่าจาก environment
$driver = $_ENV['CACHE_DRIVER'] ?? 'file';
$config = [];
switch ($driver) {
case 'redis':
$config = [
'host' => $_ENV['REDIS_HOST'] ?? 'localhost',
'port' => $_ENV['REDIS_PORT'] ?? 6379,
'password' => $_ENV['REDIS_PASSWORD'] ?? null,
'database' => $_ENV['REDIS_DB'] ?? 0
];
break;
case 'file':
$config = [
'cache_dir' => $_ENV['CACHE_DIR'] ?? '/var/cache'
];
break;
}
$cache = CacheFactory::create($driver, $config);2. Error Handling
function createSafeCache($driver, $config) {
try {
return CacheFactory::create($driver, $config);
} catch (Exception $e) {
error_log("Failed to create {$driver} cache: " . $e->getMessage());
// Fallback to memory cache
return CacheFactory::create('memory');
}
}3. Testing
class CacheFactoryTest extends TestCase {
public function testCreateFileCache() {
$cache = CacheFactory::create('file', [
'cache_dir' => '/tmp/test_cache'
]);
$this->assertInstanceOf(FileCache::class, $cache);
}
public function testCreateMemoryCache() {
$cache = CacheFactory::create('memory');
$this->assertInstanceOf(MemoryCache::class, $cache);
}
public function testCreateRedisCacheWithConfig() {
$cache = CacheFactory::create('redis', [
'host' => 'localhost',
'port' => 6379
]);
$this->assertInstanceOf(RedisCache::class, $cache);
}
}CacheFactory ช่วยให้การจัดการ Cache ในระบบเป็นไปอย่างมีระเบียบและยืดหยุ่น สามารถเปลี่ยน Cache driver ได้ง่ายโดยไม่ต้องแก้ไขโค้ดในหลายที่