返回使用数组和/或对象的方法的条件



所以我有一个单独的方法,它生成了一个缓存键,还自动应用了一个瞬态。

方法如下:

private function get_cache($id, $count)
{
$cache_key = $this->generate_cache_key($id, $count);
return get_transient($cache_key);
}

如何使该方法同时返回$cache_keyget_transient

以下是我正在努力实现的目标

  • 访问另一个方法中的$cache_key
  • 在调用该方法时,还要执行get_transient

我有一个方法,这就是我的目标:

public function delete_cache($count = 4)
{
$cache_key = $this->get_cache['cache_key'];
var_dump($cache_key);
}

所以我在想类似$instagram->get_cache['cache_key']的东西,但也保留了的原始功能

if ($cached = $instagram->get_cache($instagram->user_id, $count)) {
return $cached;
}

有人知道我如何获得另一个方法的cache_key,但仍然保留get_transient返回吗?

从函数返回多个值的概念被称为"元组";。几乎每一种语言都在某种程度上实现了这一点,有时是";记录";,有时作为";数据库行";,或者作为一个结构。对于PHP,您几乎只能使用带有字段的对象或数组,后者是最常见的。您的get_cache功能可以重新设计为:

private function get_cache($id, $count)
{
$cache_key = $this->generate_cache_key($id, $count);
return [$cache_key, get_transient($cache_key)];
}

要调用它,您需要执行以下操作:

[$cache_key, $value] = $this->get_cache('a', 4);

或者,如果使用旧版本的PHP(或者你只是不喜欢它的外观(:

list($cache_key, $value) = $this->get_cache('a', 4);

这样做的缺点是所有调用方都必须更改以支持此功能,这可能是问题,也可能不是问题。另一种选择是向执行更多工作的函数添加一个可选的回调:

private function get_cache($id, $count, callable $func = null)
{
$cache_key = $this->generate_cache_key($id, $count);
$value = get_transient($cache_key);
if(is_callable($func)){
$func($cache_key, $value);
}
return $value;
}

并称之为:

$value = $this->get_cache(
'a',
4,
static function($cache_key, $value) {
var_dump($cache_key);
}
);

虽然你正在使用WordPress,但我认为了解其他框架的功能也很有帮助。PSR-6定义了一种名为CacheItemInterface的东西,这是返回的对象形式,Symfony的缓存(你实际上可以在WordPress中使用,我有时会在大型项目中使用(使用get with callback语法。

您可以返回这两个值的数组

private function get_cache($id, $count)
{
$cache_key = $this->generate_cache_key($id, $count);
return [$cache_key, get_transient($cache_key)];
}
// ...
[$cache_key, $transient] = get_cache($id, $count);

最新更新