Система кеширования в PHP

Активный
Статус
Сообщения
516
Лайки
32

8

месяц на сайте

Руководство по созданию системы кеширования для улучшения производительности приложений.

Простое файловое кеширование

Код:
<?php
class FileCache {
    private $cacheDir;
    
    public function __construct($cacheDir = 'cache/') {
        $this->cacheDir = $cacheDir;
        if (!file_exists($cacheDir)) {
            mkdir($cacheDir, 0755, true);
        }
    }
    
    public function set($key, $value, $ttl = 3600) {
        $file = $this->cacheDir . md5($key) . '.cache';
        $data = [
            'value' => $value,
            'expires' => time() + $ttl
        ];
        file_put_contents($file, serialize($data));
    }
    
    public function get($key) {
        $file = $this->cacheDir . md5($key) . '.cache';
        
        if (!file_exists($file)) {
            return null;
        }
        
        $data = unserialize(file_get_contents($file));
        
        if ($data['expires'] < time()) {
            unlink($file);
            return null;
        }
        
        return $data['value'];
    }
    
    public function delete($key) {
        $file = $this->cacheDir . md5($key) . '.cache';
        if (file_exists($file)) {
            unlink($file);
        }
    }
    
    public function clear() {
        $files = glob($this->cacheDir . '*.cache');
        foreach ($files as $file) {
            unlink($file);
        }
    }
}

$cache = new FileCache();
$cache->set('user_1', ['name' => 'Иван', 'email' => 'ivan@example.com'], 3600);
$user = $cache->get('user_1');
?>

Кеширование с использованием Memcached

Код:
<?php
class MemcachedCache {
    private $memcached;
    
    public function __construct() {
        $this->memcached = new Memcached();
        $this->memcached->addServer('localhost', 11211);
    }
    
    public function set($key, $value, $ttl = 3600) {
        return $this->memcached->set($key, $value, $ttl);
    }
    
    public function get($key) {
        return $this->memcached->get($key);
    }
    
    public function delete($key) {
        return $this->memcached->delete($key);
    }
    
    public function flush() {
        return $this->memcached->flush();
    }
}

$cache = new MemcachedCache();
$cache->set('data', 'value', 3600);
$value = $cache->get('data');
?>

Кеширование результатов запросов

Код:
<?php
function getCachedQuery($query, $params = [], $ttl = 3600) {
    $cache = new FileCache();
    $cacheKey = 'query_' . md5($query . serialize($params));
    
    $result = $cache->get($cacheKey);
    if ($result !== null) {
        return $result;
    }
    
    $pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $result = $stmt->fetchAll();
    
    $cache->set($cacheKey, $result, $ttl);
    return $result;
}

$users = getCachedQuery("SELECT * FROM users WHERE status = ?", ['active'], 1800);
?>

Кеширование страниц

Код:
<?php
function getCachedPage($pageKey, $callback, $ttl = 3600) {
    $cache = new FileCache();
    
    $content = $cache->get($pageKey);
    if ($content !== null) {
        return $content;
    }
    
    ob_start();
    $callback();
    $content = ob_get_clean();
    
    $cache->set($pageKey, $content, $ttl);
    return $content;
}

echo getCachedPage('homepage', function() {
    // Генерация контента страницы
    echo "<h1>Главная страница</h1>";
    echo "<p>Контент страницы</p>";
}, 3600);
?>

Инвалидация кеша

Код:
<?php
class CacheManager {
    private $cache;
    private $tags = [];
    
    public function __construct() {
        $this->cache = new FileCache();
    }
    
    public function set($key, $value, $ttl = 3600, $tags = []) {
        $this->cache->set($key, $value, $ttl);
        
        foreach ($tags as $tag) {
            if (!isset($this->tags[$tag])) {
                $this->tags[$tag] = [];
            }
            $this->tags[$tag][] = $key;
            $this->cache->set("tag_$tag", $this->tags[$tag], 86400);
        }
    }
    
    public function invalidateByTag($tag) {
        $keys = $this->cache->get("tag_$tag");
        if ($keys) {
            foreach ($keys as $key) {
                $this->cache->delete($key);
            }
        }
    }
}

$cache = new CacheManager();
$cache->set('user_1', $userData, 3600, ['users', 'user_1']);
$cache->invalidateByTag('users'); // Удаляет все кеши с тегом users
?>

Кеширование API ответов

Код:
<?php
function getCachedApiResponse($url, $ttl = 3600) {
    $cache = new FileCache();
    $cacheKey = 'api_' . md5($url);
    
    $response = $cache->get($cacheKey);
    if ($response !== null) {
        return $response;
    }
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    
    $cache->set($cacheKey, $response, $ttl);
    return $response;
}

$data = json_decode(getCachedApiResponse('https://api.example.com/data', 1800));
?>

Кеширование значительно улучшает производительность приложений, уменьшая нагрузку на базу данных и внешние API.
 

1 человек читают эту тему (Всего: 1, Пользователей: 0, Гостей: 1)

Сверху