为什么80%的码农都做不了架构师?>>>   

24. Caching

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.

24.1. Cache Drivers

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

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

  • fetch($id) - Fetches an entry from the cache.

  • contains($id) - Test if an entry exists in the cache.

  • save($id, $data, $lifeTime = false) - Puts data into the cache.

  • delete($id) - Deletes a cache entry.

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

  • _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.

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 APCin 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.

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

<?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.

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

<?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.

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.

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

<?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 Xcachehere. 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.

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

<?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 Redisfrom here. Also checkA PHP extension for Redis for how you can use and install Redis PHP extension.

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

<?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 theArrayCache implementation as our example here.

<?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 thesave() method.

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

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

  • $id - The cache 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.

<?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 thecontains() method. It accepts a single argument which is the ID of the cache entry.

<?phpif ($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 thefetch() method. It also accepts a single argument just likecontains() which is the ID of the cache entry.

<?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.

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.

<?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.

<?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.

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.

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.

<?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().

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

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

<?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.

<?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 to useResultCache().

<?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.

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.

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.

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

$ ./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.

$ ./doctrine clear-cache --query

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

$ ./doctrine clear-cache --metadata

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

$ ./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.

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

$ ./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.

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.

#####################################################################################

http://notmysock.org/blog/php/user-cache-timebomb.html

转载于:https://my.oschina.net/imot/blog/219558

Doctrine官方手册 - 缓存相关推荐

  1. PhysX官方手册翻译

    PhysX官方手册翻译 本人水平有限,翻译中如果出现比较恶的句子...大家一定要查阅原文. 更新:2008-7-1   22:22  Raycasting(射线查询) 更新:2008-6-26 23: ...

  2. Unity官方手册之ParticleSystem_Collision模块

    官方文档访问总是太慢了,所以完全复制出来做查询用.建议访问官方手册https://docs.unity3d.com/Manual/index.html Collision 模块 此模块控制粒子如何与场 ...

  3. 翻译:XtraDB/InnoDB中的AUTO_INCREMENT处理方式(已提交到MariaDB官方手册)

    本文为mariadb官方手册:XtraDB/InnoDB中的AUTO_INCREMENT处理方式的译文. 原文:https://mariadb.com/kb/en/auto_increment-han ...

  4. 在虚拟机中安装gentoo简化步骤(基于官方手册)

    **************************第1部分-关于如何安装gentoo linux************************** 1-1.本步骤中只包含官方手册中最必须的内容,如 ...

  5. 翻译:用户变量(User-Defined Variable)(已提交到MariaDB官方手册)

    本文为mariadb官方手册:User-Defined Variables的译文. 原文:https://mariadb.com/kb/en/user-defined-variables/ 我提交到M ...

  6. 服务器日志文件中包含堆栈跟踪,日志框架 Logback 官方手册(第三章:Configuration)...

    以下内容翻译整理自logback官方手册,地址:logback官方手册 logback 配置 将日志请求插入应用程序代码需要相当多的计划和工作.观察表明,大约有4%的代码用于日志记录.因此,即使是一个 ...

  7. 翻译:TRUNCATE TABLE(已提交到MariaDB官方手册)

    本文为mariadb官方手册:TRUNCATE TABLE的译文. 原文:https://mariadb.com/kb/en/truncate-table/ 我提交到MariaDB官方手册的译文:ht ...

  8. 翻译:group_concat()函数(已提交到MariaDB官方手册)

    本文为mariadb官方手册:group_concat()函数的译文. 原文:https://mariadb.com/kb/en/group_concat/ 我提交到MariaDB官方手册的译文:ht ...

  9. zabbix-3.2 官方手册

    zabbix官方手册 手册分为19部分 第一部分是写介绍 1 Manual structure(可看可不看) Structure The content of this Zabbix 3.2 manu ...

最新文章

  1. 矩阵分析与多元统计 线性空间与线性变换2
  2. IIS8 使用FastCGI配置PHP环境支持 过程详解
  3. SpringMVC中@RequestMapping 6个基本用法小结
  4. 乘法器的verilog实现(并行、移位相加、查找表)
  5. IoTSharp 2.0 发布
  6. mysql-8.0.12语法_mysql-8.0.12 (免安装版) 安装详解
  7. Google Maps API 中的标注编程
  8. 微电子科学与工程是否属于计算机类专业,微电子科学与工程专业属于什么学科...
  9. 图灵科普数学宝藏书单|购书狂欢618倒计时,这份书单闭眼入
  10. 学习路线、站点推荐、工具软件、资源下载
  11. Extraneous children found when component already has explicitly named default slot. These children
  12. 汉诺塔(Hanoi Tower)
  13. LL(1)预测分析程序
  14. XDOJ 中心对称字符串
  15. cmd下访问内部数据库
  16. 中兴回应被列入被执行人名单;摩拜否认裁员 30%;LG 支持韩国对高通罚款 9 亿美元 | 雷锋早报...
  17. 软件架构设计标准 (IEEE 1471 2000) ——极简教程
  18. 中国联通全国集中综合结算系统
  19. 推荐23个精美的的国外单页网站设计作品
  20. dbPaaS实战:租户和资源管理

热门文章

  1. Struts2拦截器实现异常处理机制
  2. struts2 datetimepicker标签的使用
  3. maven优化-repositories,dependencyManagement,pluginManagement
  4. aspnetboilerplate .net core 使用原生sql
  5. 聊聊技术写作的个人体会
  6. 【差分+前缀和】BZOJ1637: [Usaco2007 Mar]Balanced Lineup
  7. 阿里云ECS部署node.js及防火墙80端口开启
  8. 2018 GDCPC 省赛总结
  9. windows下bash终端--git-bash总汇
  10. WCF双向通讯netTCP