你好,
考虑类方法,每次做一些代码准备,即实例新对象,创建数组或连接长字符串,如下所示:
class Example
{
public function methodWithPreparations($timestamp)
{
// preparations
$date = new DateTime();
$format = implode('-', array('Y', 'm', 'd', 'h', 'i', 's'));
$append = ' some text';
$append .= OtherClass::someText(); // persisten during runtime
// using function arguments
return $date->setTimestamp($timestamp)->format($format).$append;
}
}
是实现一些缓存机制来准备代码,还是现代PHP能够自己处理它?我使用 PHP 5.6,但我从未深入研究过它的内部工作原理。
像这样使用$cache
属性怎么样:
class Example
{
protected $cache;
public function methodWithPreparations($timestamp)
{
if(empty($cache = &$this->cache('chacheKey'))) {
$cache['dateTime'] = new DateTime();
$cache['format'] = implode('-', array('Y', 'm', 'd', 'h', 'i', 's'));
$cache['append'] = ' some text'.OtherClass::someText();
}
// and then
return $cache['dateTime']->setTimestamp($timestamp)
->format($cache['format']).$cache['append'];
}
}
你怎么看?
PHP 不会为你缓存这些变量。在构造函数中将它们创建为类变量,并在以后需要时重用它们。
public function __construct() {
$this->dateTime = new DateTime();
$this->dateFormat = implode('-', array('Y', 'm', 'd', 'h', 'i', 's'));
$this->append = ' some text'.OtherClass::someText();
}
public function methodWithPreparations($timestamp) {
return $this->dateTime->setTimestamp($timestamp)->format($this->dateFormat).$this->append;
}
您无需重新创建日期时间,因为您可以重复使用它。您可以为不同的日期格式制作缓存,如果不仅时间戳更改,则附加。
你使用 PHP - 所以你应该对 RFC 2616 有一定的了解。您应该了解使用 HTTP/1.1 实现的痛苦的复杂性,以及运营网站时缓存管理的问题。缓存函数的输出同样复杂,但 PHP 不会尝试实现任何机制来做到这一点。作为一种编程语言,它不需要。(有趣的是,MySQL实现的过程语言的语义确实明确允许缓存,但它的实现非常非常有限)。
PHP 不知道一个值可以缓存多长时间。它不知道会使该缓存无效的条件。它无法维护数据项与生成它的代码的关联。
那是你的工作。
出于完全相同的原因,我们不能说你的方法是否有效。节省 CPU 周期(或数据库查询或网络数据包等)通常是一个好主意。但是,例如,上面的代码会随着对象持续的时间越长而变得越来越破碎。如果它正在处理一个短暂的 Web 请求,这可能不是问题 - 但如果你正在为核反应堆编写一个监控守护进程,那么你可能不想对领带值使用缓存(并且时间相关的值应该有一个 TTL)。