2015-08-17 17:00:26 -07:00
< ? php
namespace Doctrine\Common\Cache ;
2018-11-23 12:29:20 +00:00
use Memcached ;
use function time ;
2015-08-17 17:00:26 -07:00
/**
* Memcached cache provider .
*
* @ link www . doctrine - project . org
*/
class MemcachedCache extends CacheProvider
{
2018-11-23 12:29:20 +00:00
/** @var Memcached|null */
2015-08-17 17:00:26 -07:00
private $memcached ;
/**
* Sets the memcache instance to use .
*
* @ return void
*/
public function setMemcached ( Memcached $memcached )
{
$this -> memcached = $memcached ;
}
/**
* Gets the memcached instance used by the cache .
*
* @ return Memcached | null
*/
public function getMemcached ()
{
return $this -> memcached ;
}
/**
* { @ inheritdoc }
*/
protected function doFetch ( $id )
{
return $this -> memcached -> get ( $id );
}
2015-10-08 11:40:12 -07:00
/**
* { @ inheritdoc }
*/
protected function doFetchMultiple ( array $keys )
{
2017-04-13 15:53:35 +01:00
return $this -> memcached -> getMulti ( $keys ) ? : [];
}
/**
* { @ inheritdoc }
*/
protected function doSaveMultiple ( array $keysAndValues , $lifetime = 0 )
{
if ( $lifetime > 30 * 24 * 3600 ) {
$lifetime = time () + $lifetime ;
}
return $this -> memcached -> setMulti ( $keysAndValues , $lifetime );
2015-10-08 11:40:12 -07:00
}
2015-08-17 17:00:26 -07:00
/**
* { @ inheritdoc }
*/
protected function doContains ( $id )
{
2018-11-23 12:29:20 +00:00
$this -> memcached -> get ( $id );
return $this -> memcached -> getResultCode () === Memcached :: RES_SUCCESS ;
2015-08-17 17:00:26 -07:00
}
/**
* { @ inheritdoc }
*/
protected function doSave ( $id , $data , $lifeTime = 0 )
{
if ( $lifeTime > 30 * 24 * 3600 ) {
$lifeTime = time () + $lifeTime ;
}
return $this -> memcached -> set ( $id , $data , ( int ) $lifeTime );
}
2018-11-23 12:29:20 +00:00
/**
* { @ inheritdoc }
*/
protected function doDeleteMultiple ( array $keys )
{
return $this -> memcached -> deleteMulti ( $keys )
|| $this -> memcached -> getResultCode () === Memcached :: RES_NOTFOUND ;
}
2015-08-17 17:00:26 -07:00
/**
* { @ inheritdoc }
*/
protected function doDelete ( $id )
{
2017-04-13 15:53:35 +01:00
return $this -> memcached -> delete ( $id )
|| $this -> memcached -> getResultCode () === Memcached :: RES_NOTFOUND ;
2015-08-17 17:00:26 -07:00
}
/**
* { @ inheritdoc }
*/
protected function doFlush ()
{
return $this -> memcached -> flush ();
}
/**
* { @ inheritdoc }
*/
protected function doGetStats ()
{
$stats = $this -> memcached -> getStats ();
$servers = $this -> memcached -> getServerList ();
$key = $servers [ 0 ][ 'host' ] . ':' . $servers [ 0 ][ 'port' ];
$stats = $stats [ $key ];
2018-11-23 12:29:20 +00:00
return [
2015-08-17 17:00:26 -07:00
Cache :: STATS_HITS => $stats [ 'get_hits' ],
Cache :: STATS_MISSES => $stats [ 'get_misses' ],
Cache :: STATS_UPTIME => $stats [ 'uptime' ],
Cache :: STATS_MEMORY_USAGE => $stats [ 'bytes' ],
Cache :: STATS_MEMORY_AVAILABLE => $stats [ 'limit_maxbytes' ],
2018-11-23 12:29:20 +00:00
];
2015-08-17 17:00:26 -07:00
}
}