你好,理論:類方法中PHP緩存
考慮類方法,即每次做一些代碼的準備,即例如新的對象,創建數組或連接長字符串,像這樣:
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'];
}
}
什麼你覺得呢?
不要生成類存在的值是個好主意。 – Zaki 2015-03-13 09:06:08
@Zaki:當然。我的問題是關於方法特定的值。 – Vaclav 2015-03-13 11:02:19