bigpaulie/cachebundle

此扩展包为多域名和ORM缓存提供了一些额外功能

安装: 501

依赖: 0

建议者: 0

安全性: 0

星星: 1

观察者: 3

分支: 0

开放问题: 0

类型:symfony-bundle

v1.1.0 2017-06-01 19:56 UTC

This package is auto-updated.

Last update: 2024-08-29 04:27:39 UTC


README

此扩展包通过暴露一个服务和特性来为缓存层提供一些额外功能,以便您更容易地缓存查询。

目前此扩展包适用于 Symfony 2.8.x PHP 5.6, PHP 7 和 MySQL/MariaDB

安装

安装此扩展包的首选方式是通过 composer

composer require bigpaulie/symfony-cachebundle "dev-master" --prefer-dist

在需要该包后,您应该在 AppKernel.php 中将扩展包添加到您的扩展包数组中

$bundles = array(
        ...
        new bigpaulie\CacheBundle\BigpaulieCacheBundle(),
);

在 config.yml 文件的顶部导入 services.yml

- { resource: "@BigpaulieCacheBundle/Resources/config/services.yml"}

在 parameters.yml 中添加一个新参数

memcached_servers:
        - { host: 127.0.0.1, port: 11211 }

启用/禁用特定环境的缓存

在您的 config_*.yml 文件中放置以下内容

    bigpaulie_cache:
        enable: true|false

告诉 doctrine 使用特定的缓存驱动程序

doctrine:
    orm:
        metadata_cache_driver:
            type: service
            id: doctrine.cache.driver.memcached
        query_cache_driver:
            type: service
            id: doctrine.cache.driver.memcached
        result_cache_driver:
            type: service
            id: doctrine.cache.driver.memcached

查询缓存

此扩展包遵循官方 API,具体请参阅 Doctrine 项目 中的文档

DQL 缓存

// $qb instanceof QueryBuilder

$qb->select('u')
   ->from('User', 'u')
   ->where('u.id = ?1')
   ->orderBy('u.name', 'ASC')
   ->setParameter(1, 100);
   
$query = $qb->getQuery();
$query->setQueryCaching(true);

$result = $query->getResult();

setQueryCaching() 方法支持两个额外的参数:生命周期和密钥。

$query->setQueryCaching(true, 3600, 'my_unique_key');

实体缓存

Symfony 框架默认不支持实体缓存,这里就引入了 Cacheable 特性。在您希望缓存的仓库中使用 Cacheable 特性。

use bigpaulie\CacheBundle\Doctrine\Support\Cacheable;
重写方法

find()

 find($id, $lifetime = null, \Closure $callable = null)

如果您指定了缓存生命周期,则结果将被缓存。

此外,还有一个第三个参数,您可以传递一个闭包,作为查询没有返回任何结果时的默认返回值。

findOneBy()

findOneBy(array $criteria, array $orderBy = null, $lifetime = null, \Closure $callable = null)

如果您指定了缓存生命周期,则结果将被缓存。

您还可以传递一个闭包作为第四个参数,作为查询没有返回任何结果时的默认返回值。

findAll()

findAll($lifetime = null, \Closure $callable = null)

如果您指定了缓存生命周期,则结果将被缓存。

您还可以传递一个闭包作为第二个参数,作为查询没有返回任何结果时的默认返回值。

示例用法
use bigpaulie\CacheBundle\Doctrine\Support\Cacheable;
use Doctrine\ORM\EntityRepository;

/**
 * SomeRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class SomeRepository extends EntityRepository
{
    use Cacheable;
}
// No caching
$this->getDoctrine()->getRepository('SomeBundle:SomeEntity')->find(1);

// Caching for 3600 seconds
$this->getDoctrine()->getRepository('SomeBundle:SomeEntity')->find(1, 3600);

// Caching for 3600 seconds and passing a Closure
$this->getDoctrine()->getRepository('SomeBundle:SomeEntity')->find(1, 3600, function () {
    return new NullObject();
});

贡献

欢迎为该项目做出贡献,让我们一起使它变得更好。

分支、代码、提交 pull 请求或打开问题。