【问题标题】:php object caching within constructor构造函数中的php对象缓存
【发布时间】:2012-03-07 09:26:37
【问题描述】:

我希望能够通过使用构造函数而不是某些工厂方法来使用对象的透明(可怜的人)缓存。

$a = new aClass(); 应该检查此对象是否存在于缓存中,如果不存在则创建它并将其添加到缓存中。

一些伪代码:

class aClass {
    public function __construct($someId) {
        if (is_cached($someId) {
            $this = get_cached($someId);
        } else {
            // do stuff here
            set_cached($someId, $this);
        }
    }
}

很遗憾,这是不可能的,因为您无法在 php 中重新定义 $this

有什么建议吗?

【问题讨论】:

  • 工厂有什么问题?
  • 第一,我想要透明,第二,我不想重写数十万行代码。

标签: php caching constructor factory


【解决方案1】:

这将不起作用,因为 ctors 不会返回并且您无法重新定义 $this

您可以改用静态工厂方法:

class Foo
{
    protected static $instances = array();

    public function getCachedOrNew($id)
    {
        if (!isset(self::$instances[$id])) {
            self::$instances[$id] = new self;
        }
        return self::$instances[$id];
    }
}

$foo = Foo::getCachedOrNew(1);
$foo->bar = 1;
$foo = Foo::getCachedOrNew(1);
echo $foo->bar; // 1

另一种选择是使用可以管理对象实例的依赖注入容器 (DIC)。看看The Symfony Componenent DIC.这个。

【讨论】:

  • 正如我所提到的,我不想使用工厂方法来创建对象,我想要透明缓存。但我看起来这对 php 来说是不可能的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-20
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
  • 2012-04-17
  • 2013-01-01
相关资源
最近更新 更多