ZF2中的依赖注入

时间:2013-12-17 06:53:01

标签: php dependency-injection zend-framework2

在我的应用程序中,我通过api请求获取产品列表。为了在每个页面中列出产品,我需要每次使用userid作为参数执行相同的api请求。这将增加服务器负载,因此为了避免这种情况,我需要获取产品列表并重用该实例。

如何通过引入DI或Dependency Container,通过一次调用实现此目的。

或者还有其他技术可以实现这一目标吗?我不想使用会话或数据库

1 个答案:

答案 0 :(得分:1)

好方法是使用缓存。例如:

// your service
public function getProducts($id)
{
    if ($cache = $this->cache->hasItem($id)) {
        return $this->cache->getItem($id);
    }

    // call api
    $result = $this->api->call($id);
    $this->cache->setItem($id, $result);

    return $result;
}

对于缓存实例,您可以使用Zend \ Cache