0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHPでキャッシュをMySQLに保存する方法

Last updated at Posted at 2019-12-20

概要

キャッシュを使いたいけどキャッシュサーバがない場合にsymfony/cacheのPdoAdapterを使うと簡単にDBにキャッシュを保存することができたのでメモ。

導入

composerでsymfony/cacheをインストール。

composer require symfony/cache

symfony/cacheはPSR-6なので扱いやすいPSR-16に変換するためにpsr/simple-cacheもインストールする。

composer require psr/simple-cache

以下実装例。DB名など自分の環境に読み替えてください。

<?php
require_once(__DIR__ . '/vendor/autoload.php');
use Symfony\Component\Cache\Adapter\PdoAdapter;
use Symfony\Component\Cache\Psr16Cache;
try {
    $pdo = new \PDO ('mysql:dbname=cache; host=localhost;port=3306; charset=utf8', 'user', 'passw0rd');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo '接続に成功しました。';
} catch (PDOException $e) {
    echo "接続エラー:{$e->getMessage()}";
}

$cache6 = new PdoAdapter(
    $pdo,
    $namespace = '',
    $defaultLifetime = 360,
    $options = []
);

// PSR-16に変換する
$cache16 = new Psr16Cache($cache6);

$key = 'key';
$value = 'value';

var_dump($cache16->get($key, null));
var_dump($cache16->set($key, $value));
var_dump($cache16->get($key, null));
var_dump($cache16->delete($key));

テーブルはsetの初回実行時に自動で作成される。
実行結果

接続に成功しました。
NULL
bool(true)
string(5) "value"
bool(true)

環境

PHP v7.3.2
MariaDB 10.1.38

参考

https://symfony.com/doc/current/components/cache/adapters/pdo_doctrine_dbal_adapter.html
https://symfony.com/doc/current/components/cache/psr6_psr16_adapters.html

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?