You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Zend_Cache调用getItem()报错:在数组上调用成员函数

Fixing "Call to a member function getItem() on array" with Zend_Cache Filesystem Adapter

我一眼就看出问题所在了——你在工厂类里拿错东西啦!你现在用$config['caches']['FilesystemCache']拿到的只是缓存的配置数组,不是真正可以调用方法的缓存对象,难怪调用getItem()会报“在数组上调用成员函数”的错误。

问题根源

你在AccessControlFactory里的这段代码是关键错误:

$cache = $config['caches']['FilesystemCache'];

这行代码获取的是你在global.php里定义的缓存配置(比如缓存目录、TTL这些参数),本质是一个数组,而不是Zend已经帮你实例化好的FilesystemCache对象。当你把这个数组传给AccessControl,再调用$this->cache->getItem()时,就相当于在对数组调用对象方法,自然会触发错误。

修复步骤

只需要修改工厂类中获取缓存的方式,直接从ServiceManager容器中获取已经初始化完成的缓存实例:

  1. 替换工厂类中的缓存获取代码
    把原来的$cache = $config['caches']['FilesystemCache'];改成:
$cache = $container->get('FilesystemCache');

Zend的ServiceManager会自动根据你在global.php里的配置,帮你实例化Filesystem适配器,并且加载好serializer插件,拿到的就是可以直接使用的缓存对象。

  1. 修改后的完整工厂类代码
<?php
namespace User\Service;

use User\Controller\Plugin\AuthPlugin;
use User\Model\GrantsTable;
use User\Model\UserTable;
use Zend\Authentication\AuthenticationService;
use Zend\ServiceManager\Factory\FactoryInterface;
use Interop\Container\ContainerInterface;

class AccessControlFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $config = $container->get('config');
        $userTable = $container->get(UserTable::class);
        $grantsTable = $container->get(GrantsTable::class);
        // 这里改成从容器获取缓存实例,而不是配置数组
        $cache = $container->get('FilesystemCache');
        $userplugin = $container->get(AuthPlugin::class);
        
        return new AccessControl($userTable, $grantsTable, $cache, $userplugin);
    }
}

额外验证要点

  • 确保你的global.php顶部已经引入了Filesystem类:
use Zend\Cache\Storage\Adapter\Filesystem;
  • 检查cache_dir指定的./data/cache目录是否存在,并且Web服务器有读写权限(如果不存在,手动创建并设置权限,比如chmod 755 data/cache)。

这样修改之后,你在AccessControl的init方法中调用$this->cache->getItem('rbac_container', $result)就可以正常工作了。

内容的提问来源于stack exchange,提问作者pia-sophie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 17:37:32