Skip to content

Instantly share code, notes, and snippets.

@oshiro-kazuma
Created August 2, 2012 09:38
Show Gist options
  • Save oshiro-kazuma/3235907 to your computer and use it in GitHub Desktop.
Save oshiro-kazuma/3235907 to your computer and use it in GitHub Desktop.
PHPでmemcachedを使うとき
<?php
class PdoDao {
const user = "hogehoge";
const pass = "hogehoge";
const memSec = 10;
private $pdo;
private $m;
function __construct() {
$this->pdo =
new PDO('mysql:host=localhost;dbname=test', self::user, self::pass);
$this->m = new Memcache;
$this->m->connect('localhost', 11211);
}
function __destruct() {
$this->pdo = null;
$this->m = null;
}
/**
* すべて検索
*/
function findAll() {
if($this->getMemcachedStatus()) {
$data = $this->m->get("ArticleAll");
}
if(!$data) {
echo "findAll:: Get Database.". PHP_EOL;
$stmt = $this->pdo->prepare("select * from article;");
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($this->getMemcachedStatus()) {
echo "findAll:: Set Memcache.". PHP_EOL;
$this->m->set("ArticleAll", $data, false, self::memSec);
}
}
return $data;
}
/**
* IDを指定して検索
* @param id
*/
function findId($id) {
if($this->getMemcachedStatus()) {
$data = $this->m->get($id);
}
if(!$data) {
echo "findId:: Get Database.". PHP_EOL;
$stmt = $this->pdo->prepare("select * from article where id = :id");
$stmt->bindParam(":id", $id);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($this->getMemcachedStatus()) {
echo "findId:: Set Memcache.". PHP_EOL;
$this->m->set($id, $data, false, self::memSec);
}
}
return $data;
}
/**
* memcached が使用可能かどうかを返す
*/
function getMemcachedStatus() {
if (!is_null($this->m)) {
return $this->m->getServerStatus("localhost", 11211) ? true : false;
}
return false;
}
}
<?php
require_once('PdoDao.php');
$pdo = new PdoDao();
echo "## findId テスト". PHP_EOL;
$retVal = $pdo->findId(1);
foreach($retVal as $ret) {
var_dump($ret);
}
echo "## findAll テスト". PHP_EOL;
$retVal = $pdo->findAll();
foreach($retVal as $ret) {
var_dump($ret);
}
@oshiro-kazuma
Copy link
Author

memcachedでDB問い合わせ結果をキャッシュ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment