Zend Framework——缓存与配置

Zend_Cache

在Zend Framework中缓存由前端(Core,Output, File, Function 和 Class)操作,同时通过后端适配器(File, Sqlite, Memcache…)和 一个灵活的IDs和Tags系统(标识符和标记系统)存储缓存纪录。

Zend_Cache前端

主要调用 Zend_Cache::factory() 取得前端,如果你想缓存特殊值(带 “automatic_serialization” 选项的布尔值)或不能用上述紧缩结构的空字符串,你需要正式地测试缓存记录。

1.Zend_Cache_Core

参数:1.caching(测试用);2.lifetime(缓存时间);3.cache_id_prefix(前缀ID);4.automatic_serialization(序列化)

$frontendOptions = array(
   'lifeTime' => 7200, // 两小时的缓存生命期
   'automatic_serialization' => true
);

$backendOptions = array(
    'cache_dir' => './tmp/' // 放缓存文件的目录
);

// 取得一个Zend_Cache_Core 对象
$cache = Zend_Cache::factory('Core','File', $frontendOptions, $backendOptions);

2.Zend_Cache_Frontend_Output
Zend_Cache_Frontend_Output 是一个输出捕捉前端.它在PHP中使用输出缓冲捕获start() 和 end() 方法间的一切输出.

$frontendOptions = array(
   'lifeTime' => 30,                  // cache lifetime of 30 seconds
   'automatic_serialization' => false  // this is the default anyway s
);
// 翻译时实验系统为Windows,请使用Windows的读者修改cacheDir的路径为实际的路径
$backendOptions = array('cache_dir' => './tmp/');

$cache = Zend_Cache::factory('Output', 
                             'File', 
                             $frontendOptions, 
                             $backendOptions);

// 传递一个唯一标识符给start()方法
if(!$cache->start('mypage')) {
    // output as usual:

    echo 'Hello world! ';
    echo 'This is cached ('.time().') ';

    $cache->end(); // the output is saved and sent to the browser
}

Zend_Cache后端

Zend_Cache_Backend_File 参数:cache_dir

数据缓存

// 查看一个缓存是否存在:
// 紧凑结构(如果缓存空字符串和/或布尔值,则不适用)
if(!$result = $cache->load('myresult')) {

    // 缓存不命中;连接到数据库

    $db = Zend_Db::factory( [...] );

    $result = $db->fetchAll('SELECT * FROM huge_table');

    $cache->save($result, 'myresult');

} else {

    // cache hit! shout so that we know
    echo "This one is from cache!\n\n";

}

// 完整的结构(无论如何都适用)
if (!($cache->test($id))) {

    // 缓存不命中

    // 重新取出 $data

    $cache->save($data);

} else {

    // 缓存命中

    $data = $cache->load($id);

}

print_r($result);

缓存取消

因为设计问题,在有些情况下(例如使用非 HTTP/200 返回代码时),你可能需要取消当前缓存处理,所以 我们引入这个特别的前端,cancel()方法。

// [...] // require, configuration and factory

$cache->start();

// [...]

if ($someTest) {
    $cache->cancel();
    // [...]
}

// [...]

标记纪录

save()方法接受可选的第四个参数:$ specificLifetime = false,它为此特定缓存记录设置特定的生命周期)

$cache->save($huge_data, 'myUniqueID', array('tagA', 'tagB', 'tagC'));

缓存清理

//清除一个记录
$cache->remove('idToRemove')

// 清除所有缓存纪录
$cache->clean(Zend_Cache::CLEANING_MODE_ALL);

// 仅清除过期的
$cache->clean(Zend_Cache::CLEANING_MODE_OLD);

//如果你想删除标记为'tagA'和'tagC'的缓存项
$cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('tagA', 'tagC'));

//如果你想删除标记不为'tagA'和'tagC'的缓存项
$cache->clean(Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG, array('tagA', 'tagC'));

其他Zend_Cache前端

1.Zend_Cache_Frontend_Function

Zend_Cache_Frontend_Function缓存函数调用的结果。 它有一个名为call()的main方法,它接受一个函数名和数组中调用的参数。

$cache->call('veryExpensiveFunc', array(1, 'foo', 'bar'))

2.Zend_Cache_Frontend_Class

Zend_Cache_Frontend_Class与Zend_Cache_Frontend_Function不同,因为它允许缓存对象和静态方法调用。

参数:cached_entity (required)

如果设置为类名,我们将缓存一个抽象类,并将只使用静态调用;如果设置为对象,我们将缓存此对象方法

class test {

    // Static method
    public static function foobar($param1, $param2) {
        echo "foobar_output($param1, $param2)";
        return "foobar_return($param1, $param2)";
    }

}

// [...]
$frontendOptions = array(
    'cached_entity' => 'Test' //1. The name of the class
     'cached_entity' => new Test() //2. An instance of the class
);
// [...]

// The cached call
$result = $cache->foobar('1', '2');

3.Zend_Cache_Frontend_File

Zend_Cache_Frontend_File是由“主文件”的修改时间驱动的前端。
例如,您有一个XML配置文件,该文件由一个返回“配置对象”的函数解析(与Zend_Config一样)。使用Zend_Cache_Frontend_File,您可以将“配置对象”存储到缓存中(以避免每次解析XML配置文件),但是对“主文件”有一种强烈的依赖性​​。因此,如果修改了XML配置文件,则会立即使缓存失效。

4.Zend_Cache_Frontend_Page

Zend_Cache_Frontend_Page与Zend_Cache_Frontend_Output类似,但设计用于完整页面。使用Zend_Cache_Frontend_Page仅缓存单个块是不可能的。

另一方面,使用 SERVER[REQUESTURI] S E R V E R [ ′ R E Q U E S T U R I ′ ] 和 ( 取 决 于 选 项 ) _GET等自动计算“缓存ID”。此外,您只能调用start(),因为当页面结束时,end()调用是完全自动的。

/*
 * you should avoid putting too many lines before the cache section.
 * For example, for optimal performances, "require_once" or 
 * "Zend_Loader::loadClass" should be after the cache section.
 */

$frontendOptions = array(
   'lifetime' => 7200,
   'debug_header' => true, // for debugging
   'regexps' => array(
       // cache the whole IndexController
       '^/$' => array('cache' => true),

       // cache the whole IndexController
       '^/index/' => array('cache' => true),

       // we don't cache the ArticleController...
       '^/article/' => array('cache' => false),

       // ... but we cache the "view" action of this ArticleController
       '^/article/view/' => array(              
           'cache' => true,

           // and we cache even there are some variables in $_POST
           'cache_with_post_variables' => true,

           // but the cache will be dependent on the $_POST array 
           'make_id_with_post_variables' => true 
       )
   )
);

$backendOptions = array(
    'cache_dir' => '/tmp/'
);

// getting a Zend_Cache_Frontend_Page object
$cache = Zend_Cache::factory('Page', 
                             'File', 
                             $frontendOptions, 
                             $backendOptions);

$cache->start();
// if the cache is hit, the result is sent to the browser and the 
// script stop here

// [...] the end of the bootstrap file 
// these lines won't be executed if the cache is hit

Zend_Config

这个模块主要用于环境配置的加载与引用
方法:
1.get()

如果数据元素不存在,它将返回提供的缺省值,例如:
$host = $config->database->get('host', 'localhost')

2.merge()

如果你有两个Zend_Config对象,你可以用merge()函数把它们合并成一个单个的对象。
例如,对config和localConfig,使用$config->merge($localConfig),你可以把数据从localConfig合并到config。在localConfig中的条目将覆盖在config中同名的条目。

Zend_Config对象还可以使用count()函数和PHP语句如foreach

继承特性
Zend_Config函数家族把配置数据组织成节(section)。Zend_Config适配器对象可以带一个指定的节加载,或者带有多个指定的节,或者所有节(如果没有指定(null))。

Zend_Config适配器类支持单继承模型,一个继承的节可以重写从父节继承过来的值。象PHP类继承,一个节可以从一个父节继承,这个父节可能是从祖父节继承的,等等,但是多重继承(例如,节C直接从父节A和B继承)不被支持。

如果数据只有一节时,直接把配置数据写入php文件,绕过Config直接使用数据可能会更好;
但是如果有多组数据,因为数据继承的关系,该模块的优势大大增加,此时有4种方法:

1.直接把写好的数组放入构造器变量中

// 给出一个配置数据的数组
$configArray = array(
    'webhost'  => 'www.example.com',
    'database' => array(
        'adapter' => 'pdo_mysql',
        'params'  => array(
            'host'     => 'db.example.com',
            'username' => 'dbuser',
            'password' => 'secret',
            'dbname'   => 'mydatabase'
        )
    )
);

// 基于配置数据创建面向对象的 wrapper 
$config = new Zend_Config($configArray);

// 输出配置数据 (结果在'www.example.com'中)
echo $config->webhost;

// 使用配置数据来连接数据库
$db = Zend_Db::factory($config->database->adapter,
                       $config->database->params->toArray());

// 另外的用法:简单地传递 Zend_Config 对象。
// Zend_Db factory 知道如何翻译它。
$db = Zend_Db::factory($config->database);

2.引入php文件
$config = new Zend_Config(require 'config.php');

// config.php
return array(
    'webhost'  => 'www.example.com',
    'database' => array(
        'adapter' => 'pdo_mysql',
        'params'  => array(
            'host'     => 'db.example.com',
            'username' => 'dbuser',
            'password' => 'secret',
            'dbname'   => 'mydatabase'
        )
    )
);

3.引入ini文件

默认的键分离器字符是句号(.)。然而,这个可以通过$options['nestSeparator'] 被修改。例如:

$options['nestSeparator'] = ':';
$config = new Zend_Config_Ini('/path/to/config.ini', 'staging', $options);

config.ini文件

; 生产站点配置数据
[production]
webhost                  = www.example.com
database.adapter         = pdo_mysql
database.params.host     = db.example.com
database.params.username = dbuser
database.params.password = secret
database.params.dbname   = dbname

; 开发站点配置数据从生产站点配置数据集成并如果需要可以重写
[staging : production]
database.params.host     = dev.example.com
database.params.username = devuser
database.params.password = devsecret

调用

$config = new Zend_Config_Ini('/path/to/config.ini', 'staging');

echo $config->database->params->host;   // 输出 "dev.example.com"
echo $config->database->params->dbname; // 输出 "dbname"

4.引入xml文件

config.xml文件 1

<?xml version="1.0"?>
<configdata>
    <production>
        <webhost>www.example.com</webhost>
        <database>
            <adapter>pdo_mysql</adapter>
            <params>
                <host>db.example.com</host>
                <username>dbuser</username>
                <password>secret</password>
                <dbname>dbname</dbname>
            </params>            
        </database>
    </production>
    <staging extends="production">
        <database>
            <params>
                <host>dev.example.com</host>
                <username>devuser</username>
                <password>devsecret</password>
            </params>            
        </database>
    </staging>
</configdata>

config.xml文件 2

<?xml version="1.0"?>
<configdata>
    <production webhost="www.example.com">
        <database adapter="pdo_mysql">
            <params host="db.example.com" username="dbuser" password="secret" dbname="dbname"/>
        </database>
    </production>
    <staging extends="production">
        <database>
            <params host="dev.example.com" username="devuser" password="devsecret"/>
        </database>
    </staging>
</configdata>

config.xml文件 3

<?xml version="1.0"?>
<configdata>
    <production>
        <webhost>www.example.com</webhost>
        <database>
            <adapter value="pdo_mysql"/>
            <params>
                <host value="db.example.com"/>
                <username value="dbuser"/>
                <password value="secret"/>
                <dbname value="dbname"/>
            </params>
        </database>
    </production>
    <staging extends="production">
        <database>
            <params>
                <host value="dev.example.com"/>
                <username value="devuser"/>
                <password value="devsecret"/>
            </params>
        </database>
    </staging>
</configdata>

调用

$config = new Zend_Config_Xml('/path/to/config.xml', 'staging');

echo $config->database->params->host;   // 输出 "dev.example.com"
echo $config->database->params->dbname; // 输出 "dbname"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值