Doctrine 缓存

8 篇文章 0 订阅
6 篇文章 0 订阅

Doctrine provides cache drivers in the Common package for some of the most popular caching implementations such as APC, Memcache and Xcache. We also provide an ArrayCache driver which stores the data in a PHP array. Obviously, the cache does not live between requests but this is useful for testing in a development environment.

Doctrine在Common包下面提供了一些缓存驱动并且实现了一些流行的缓存,如:APC, Memcache, Xcache。也提供ArrayCache驱动,ArrayCache驱动存储在php的数组里面。显然,缓存不会在不同的请求中存在。但是对于开发环境测试非常有用。

24.1. Cache Drivers

The cache drivers follow a simple interface that is defined in Doctrine\Common\Cache\Cache. All the cache drivers extend a base class Doctrine\Common\Cache\AbstractCache which implements the before mentioned interface.

缓存驱动的接口定义在Doctrine\Common\Cache\Cache. 所有的缓存驱动继承类Doctrine\Common\Cache\AbstractCache, 该类实现了Cache接口。

The interface defines the following methods for you to publicly use.

接口定义了下面的方法供你使用.

  • fetch($id) - Fetches an entry from the cache.
  • fetch($id)-从缓存中获得一条记录。
  • contains($id) - Test if an entry exists in the cache.
  • contains($id)-判断记录是否存在
  • save($id, $data, $lifeTime = false) - Puts data into the cache.
  • save($id, $data, $lifeTime=false)-将数据存入缓存
  • delete($id) - Deletes a cache entry.
  • delete($id)-删除缓存

Each driver extends the AbstractCache class which defines a few abstract protected methods that each of the drivers must implement.

每一个驱动都 需要继承AbstractCache类并且实现该类定义的一些受保护的抽象方法。

  • _doFetch($id)
  • _doContains($id)
  • _doSave($id, $data, $lifeTime = false)
  • _doDelete($id)

The public methods fetch()contains(), etc. utilize the above protected methods that are implemented by the drivers. The code is organized this way so that the protected methods in the drivers do the raw interaction with the cache implementation and the AbstractCache can build custom functionality on top of these methods.

公共的方法fetch(), contains()等利用上面受保护的方法去实现,这样的代码组织方式使得驱动里的受保护方法可以做最原始的缓存实现。AbstrachCache类可以定制上面那些方法的功能。

24.1.1. APC

In order to use the APC cache driver you must have it compiled and enabled in your php.ini. You can read about APC in the PHP Documentation. It will give you a little background information about what it is and how you can use it as well as how to install it.

为了使用APC缓存驱动你必须编译和在php.ini中激活它,你可以阅读这篇文章  in the PHP Documentation ,他可以提供一些背景知识让你怎么去安装和使用。

Below is a simple example of how you could use the APC cache driver by itself.

西面是一个简单的例子怎么去使用APC 缓存。

<?php
$cacheDriver = new \Doctrine\Common\Cache\ApcCache();
$cacheDriver->save('cache_id', 'my_data');

24.1.2. Memcache

In order to use the Memcache cache driver you must have it compiled and enabled in your php.ini. You can read about Memcache ` on the PHP website <http://php.net/memcache>`_. It will give you a little background information about what it is and how you can use it as well as how to install it.

为了使用Memcache缓存,你必须去编译和在php.ini中激活它,你可以在php官网上了解memcache的相关信息<http://php.net/memcache>。

Below is a simple example of how you could use the Memcache cache driver by itself.

西面是一个简单的例子怎么去使用memcache缓存

<?php
$memcache = new Memcache();
$memcache->connect('memcache_host', 11211);

$cacheDriver = new \Doctrine\Common\Cache\MemcacheCache();
$cacheDriver->setMemcache($memcache);
$cacheDriver->save('cache_id', 'my_data');

24.1.3. Memcached

Memcached is a more recent and complete alternative extension to Memcache.

Memcached是一个最新最完整的Memcache扩展

In order to use the Memcached cache driver you must have it compiled and enabled in your php.ini. You can read about Memcached ` on the PHP website <http://php.net/memcached>`_. It will give you a little background information about what it is and how you can use it as well as how to install it.

为了使用Memcached缓存你必须编译和在php.ini中激活它,你可以在php官网上了解memcache的相关信息<http://php.net/memcached>, 如何安装是使用。

Below is a simple example of how you could use the Memcached cache driver by itself.

下面是一个简单的例子告诉你如何去使用Memcached缓存

<?php
$memcached = new Memcached();
$memcached->addServer('memcache_host', 11211);

$cacheDriver = new \Doctrine\Common\Cache\MemcachedCache();
$cacheDriver->setMemcached($memcached);
$cacheDriver->save('cache_id', 'my_data');

24.1.4. Xcache

In order to use the Xcache cache driver you must have it compiled and enabled in your php.ini. You can read about Xcache here. It will give you a little background information about what it is and how you can use it as well as how to install it.

为了好似用Xcache缓存,你必须编译和在php.ini中激活它,你可以在here了解Xcache的背景知识和如何去安装使用他。

Below is a simple example of how you could use the Xcache cache driver by itself.

下面是一个简单的例子如何使用Xcache

<?php
$cacheDriver = new \Doctrine\Common\Cache\XcacheCache();
$cacheDriver->save('cache_id', 'my_data');

24.1.5. Redis

In order to use the Redis cache driver you must have it compiled and enabled in your php.ini. You can read about what is Redis from here. Also check A PHP extension for Redis for how you can use and install Redis PHP extension.

为了使用readis缓存,你必须编译和在php.ini中激活它,参考网站:A PHP extension for Redis

Below is a simple example of how you could use the Redis cache driver by itself.

下面是一个简单的例子如何使用redis缓存

<?php
$redis = new Redis();
$redis->connect('redis_host', 6379);

$cacheDriver = new \Doctrine\Common\Cache\RedisCache();
$cacheDriver->setRedis($redis);
$cacheDriver->save('cache_id', 'my_data');

24.2. Using Cache Drivers

In this section we’ll describe how you can fully utilize the API of the cache drivers to save cache, check if some cache exists, fetch the cached data and delete the cached data. We’ll use the ArrayCacheimplementation as our example here.

这个章节中我们描述了如何利用缓存驱动的API去保存,检查缓存是否存在,获得缓存数据,删除缓存数据。在我们的例子中将使用ArrayCache

<?php
$cacheDriver = new \Doctrine\Common\Cache\ArrayCache();

24.2.1. Saving

To save some data to the cache driver it is as simple as using the save() method.

保存数据到缓冲中使用save()方法

<?php
$cacheDriver->save('cache_id', 'my_data');

The save() method accepts three arguments which are described below.

save()方法接受三个参数:

  • $id - The cache id  (缓存id)
  • $data - The cache entry/data.(缓存数据)
  • $lifeTime - The lifetime. If != false, sets a specific lifetime for this cache entry (null => infinite lifeTime).(缓存的过期时间)

You can save any type of data whether it be a string, array, object, etc.

你可以保存任意类型数据,string,array,object等等

<?php
$array = array(
    'key1' => 'value1',
    'key2' => 'value2'
);
$cacheDriver->save('my_array', $array);

24.2.2. Checking

Checking whether some cache exists is very simple, just use the contains() method. It accepts a single argument which is the ID of the cache entry.

检查缓存是否存在非常简单,使用contains()放,他接受一个缓存id参数

<?php
if ($cacheDriver->contains('cache_id')) {
    echo 'cache exists';
} else {
    echo 'cache does not exist';
}

24.2.3. Fetching

Now if you want to retrieve some cache entry you can use the fetch() method. It also accepts a single argument just like contains() which is the ID of the cache entry.

如果你想获得缓存数据你可以使用fetch方法,像contains()方法一个接受一个id参数

<?php
$array = $cacheDriver->fetch('my_array');

24.2.4. Deleting

As you might guess, deleting is just as easy as saving, checking and fetching. We have a few ways to delete cache entries. You can delete by an individual ID, regular expression, prefix, suffix or you can delete all entries.

就像是想象中那样,删除跟保存,检查和获得一样简单。我们有好多方法去删除缓存数据,你可以通过id,正则表达式,前缀,后缀,或者你可以删除所有的数据。

24.2.4.1. By Cache ID
<?php
$cacheDriver->delete('my_array');
24.2.4.2. All

If you simply want to delete all cache entries you can do so with the deleteAll() method.

如果你想删除所有的缓存你可以使用deleteAll方法

<?php
$deleted = $cacheDriver->deleteAll();

24.2.5. Namespaces

If you heavily use caching in your application and utilize it in multiple parts of your application, or use it in different applications on the same server you may have issues with cache naming collisions. This can be worked around by using namespaces. You can set the namespace a cache driver should use by using thesetNamespace() method.

如果你的应用程序大量的使用缓存和在你的应用程序的多个部分利用缓存,或者不同的应用程序在一台服务器上面,你可能会遇到缓存名重复的问题,你可以使用命名空间,可以给一个缓存驱动通过setNamesapce()方法设置命名空间。

<?php
$cacheDriver->setNamespace('my_namespace_');

24.3. Integrating with the ORM

The Doctrine ORM package is tightly integrated with the cache drivers to allow you to improve performance of various aspects of Doctrine by just simply making some additional configurations and method calls.

Doctrine的ORM包已经集成了缓存驱动允许你改善doctrine很多方面的性能。你只需要做一些简单的配置和方法的调用。

24.3.1. Query Cache

It is highly recommended that in a production environment you cache the transformation of a DQL query to its SQL counterpart. It doesn’t make sense to do this parsing multiple times as it doesn’t change unless you alter the DQL query.

强烈建立在生成环境缓存DQL生成的sql语句,在你改变DQL查询前,再通过大量的时间去解析DQL语句没有任何意义。

This can be done by configuring the query cache implementation to use on your ORM configuration.

可用通过下面的配置去缓存查询语句。

<?php
$config = new \Doctrine\ORM\Configuration();
$config->setQueryCacheImpl(new \Doctrine\Common\Cache\ApcCache());

24.3.2. Result Cache

The result cache can be used to cache the results of your queries so that we don’t have to query the database or hydrate the data again after the first time. You just need to configure the result cache implementation.

将查询的结果缓存起来我们不需要再去数据库里面进行查询了。你需要做一些配置去实现结果缓存。

<?php
$config->setResultCacheImpl(new \Doctrine\Common\Cache\ApcCache());

Now when you’re executing DQL queries you can configure them to use the result cache.

现在当你执行DQL查询时,你可以配置它进行查询结果缓存。

<?php
$query = $em->createQuery('select u from \Entities\User u');
$query->useResultCache(true);

You can also configure an individual query to use a different result cache driver.

你也可以配置个别的查询使用不同的缓存驱动。

<?php
$query->setResultCacheDriver(new \Doctrine\Common\Cache\ApcCache());

Setting the result cache driver on the query will automatically enable the result cache for the query. If you want to disable it pass false to useResultCache(). 在查询上面设置了缓存驱动将自动的激活查询结果进行缓存。如果你想要禁用,那么传递false到useResultCache方法中。

<?php
$query->useResultCache(false);

If you want to set the time the cache has to live you can use the setResultCacheLifetime() method.

如果你想设置缓存时间,你可以使用setResultCacheLifetime()方法

<?php
$query->setResultCacheLifetime(3600);

The ID used to store the result set cache is a hash which is automatically generated for you if you don’t set a custom ID yourself with the setResultCacheId() method.

如果你不在setResultCacheId()方法中提供id,那么doctrine会自动的生成一个hash的值。

<?php
$query->setResultCacheId('my_custom_id');

You can also set the lifetime and cache ID by passing the values as the second and third argument touseResultCache().

你也可以通过设置useResultCache()方法的第二和第三个参数设置缓存生存时间和缓存ID

<?php
$query->useResultCache(true, 3600, 'my_custom_id');

24.3.3. Metadata Cache

Your class metadata can be parsed from a few different sources like YAML, XML, Annotations, etc. Instead of parsing this information on each request we should cache it using one of the cache drivers.

你类的一些metadata信息解析来自不同的源文件,如YAML,XML,Annotations等等。如果不想每个请求都解析这些信息,我们需要使用缓存

Just like the query and result cache we need to configure it first.

就像查询和结果缓存一样,我们首先需要配置

<?php
$config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ApcCache());

Now the metadata information will only be parsed once and stored in the cache driver.

现在metadata信息只在第一次解析的时候就存储在缓存中了

24.4. Clearing the Cache

We’ve already shown you previously how you can use the API of the cache drivers to manually delete cache entries. For your convenience we offer a command line task for you to help you with clearing the query, result and metadata cache.

我们已经在前面学些了如何通过缓存API去手动的删除缓存数据,为了方便,我们提供了命令行模式帮助你清除query,result,metadata缓存,

From the Doctrine command line you can run the following command.

在doctrine的命令行,你可以是运行下面的命令

$ ./doctrine clear-cache

Running this task with no arguments will clear all the cache for all the configured drivers. If you want to be more specific about what you clear you can use the following options.

不带参数运行改名了将会清除所有的缓存,如果你想指定清除什么缓存,可以传递下面这些参数。

To clear the query cache use the --query option.

清除query 缓存使用--query选项

$ ./doctrine clear-cache --query

To clear the metadata cache use the --metadata option.

清除metadata缓存使用--metadata选项

$ ./doctrine clear-cache --metadata

To clear the result cache use the --result option.

清除result cache使用 --result选项

$ ./doctrine clear-cache --result

When you use the --result option you can use some other options to be more specific about what queries result sets you want to clear.

当你使用--result选项的时候,你可以使用一些其他的选项指定哪些查询结果需要清除

Just like the API of the cache drivers you can clear based on an ID, regular expression, prefix or suffix.

就像api的缓存一样,你可以通过id,正则表达式,前缀,后缀来选择性的清除

$ ./doctrine clear-cache --result --id=cache_id

Or if you want to clear based on a regular expressions.

如果你想通过正则表达式的方式:

$ ./doctrine clear-cache --result --regex=users_.*

Or with a prefix.

或者前缀

$ ./doctrine clear-cache --result --prefix=users_

And finally with a suffix.

或者后缀

$ ./doctrine clear-cache --result --suffix=_my_account

Using the --id--regex, etc. options with the --query and --metadata are not allowed as it is not necessary to be specific about what you clear. You only ever need to completely clear the cache to remove stale entries.

使用--id, --regex等等选项在--query和--metadata不允许。因为没有必要去指定你想清除什么,你只需要完全的删除缓存去删除每一条

24.5. Cache Slams

Something to be careful of when utilizing the cache drivers is cache slams. If you have a heavily trafficked website with some code that checks for the existence of a cache record and if it does not exist it generates the information and saves it to the cache. Now if 100 requests were issued all at the same time and each one sees the cache does not exist and they all try and insert the same cache entry it could lock up APC, Xcache, etc. and cause problems. Ways exist to work around this, like pre-populating your cache and not letting your users requests populate the cache.

需要注意当使用缓存出现缓存碰撞,如果你有一个并发非常高的网站。如果缓存不存在,就会生成缓存信息并保存。现在,如果你的网站有100个请求同时的检查到了缓存不存在并且尝试保存相同的缓存信息,那么将锁住APC,Xcache等等,这将会导致一些问题。一个现成的解决方案是通过预先的填充缓存,而不是通过用户请求来填充缓存。

You can read more about cache slams in this blog post.

你可以阅读这个博客获得更多信息

 in this blog post.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值