Amazon LinuxでcakePHPからmemcachedを使うまでの日記 | エモンのブログ(スマホアプリ作成日記)

エモンのブログ(スマホアプリ作成日記)

エモンのブログです。

GooglePlayとAppStoreにアプリをリリースしてます。
「詰将棋パラダイス」4500問無料で公開。
「みんなのしょうぎ」投票型の将棋対局。いずれもソーシャルアプリなので、ソーシャルゲーム作成に興味があるかたは是非ご覧ください。

◯Apacheのインストール
sudo yum -y install httpd
sudo /etc/rc.d/init.d/httpd start

自動起動をONにしておく
chkconfig httpd on


◯PHPのインストール
yum install php


◯memcachedのインストール
yum -y install memcached

PHPから使えるようにするために以下を実行
yum install php-pecl-memcache

※これがないと Class 'Memcache' not found もしくは Cache engine default is not properly configured と言われる。

◯memcachedの起動
memcached -d -m 64 -p 11211 -u memcached

自動起動するようにしておく
chkconfig --level 2345 memcached on


◯PHPのタイムゾーンの設定
/etc/php.ini にて
date.timezone = "Asia/Tokyo"


--
※cakeのディレクトリを配置
--

◯cakephpキャッシュに書き込み権限を追加する
chmod -R 777 [cake]/app/tmp/


◯Security.saltを指定する、Security.cipherSeed'を変更する
[cake]/app/Config/core.phpにて
Security.salt、Security.cipherSeed'を適当に変更する

◯httpd.confの最後に
<Directory "/var/www/html/cattweet">
Options FollowSymLinks
AllowOverride All
</Directory>
を追加してhttpdをrestart

◯memcachedをcakePHPから使う
Vendor にmemcachedマネージャファイルを追加する
MemcacheManager.php
class MemcacheManager {
private static $cache = null;

private function __construct(){}

static function getInstance(){
if(MemcacheManager::$cache == null){
MemcacheManager::$cache = new Memcache;
MemcacheManager::$cache -> connect('localhost', '11211');
}
return MemcacheManager::$cache;
}
function get($key){
return MemcacheManager::$cache -> get($key);
}
function set($key, $var, $flag = null, $expire = '3600'){
return MemcacheManager::$cache -> set($key, $var, $flag, $expire);
}
function close(){
return MemcacheManager::$cache -> close();
}
function flush() {
return MemcacheManager::$cache -> flush();
}
}


◯config/core.phpにて以下のコメントアウトをはずす
Cache::config('default', array(
'engine' => 'Memcache', //[required]
'duration'=> 3600, //[optional]
'probability'=> 100, //[optional]
'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string
'servers' => array(
'127.0.0.1:11211' // localhost, default port 11211
), //[optional]
'compress' => false, // [optional] compress data in Memcache (slower, but uses less memory)
'persistent' => true, // [optional] set this to false for non-persistent connections
));


◯Modelにて
public function get($key) {
$cache = MemcacheManager::getInstance();
return $cache->get($key);
}

public function set($key, $value) {
$cache = MemcacheManager::getInstance();
$cache->set($key, $value);
}