Zend Framework 2 - 符合缓存的服务工厂

Lan*_*nbo 3 php zend-framework-modules zend-framework2

zend文件application.config.php提供了一些缓存配置的方法,我发现它非常适合生产系统:

return array(
        'modules' => array(
                'Application',
        ),
        'module_listener_options' => array(
                'module_paths' => array(
                        './module',
                        './vendor'
                ),
                'config_glob_paths' => array('config/autoload/{,*.}{global,local}.php'),
                'config_cache_enabled' => true,
                'config_cache_key' => md5('config'),
                'module_map_cache_enabled' => true,
                'module_map_cache_key' => md5('module_map'),
                'cache_dir' => './data/cache',
        ),
);
Run Code Online (Sandbox Code Playgroud)

但是,激活会立即导致错误

Fatal error: Call to undefined method Closure::__set_state()
Run Code Online (Sandbox Code Playgroud)

这与作为闭包编写的工厂有关,如下所示:

'service_manager' => array(
    'factories' => array(
        'auth.service' => function($sm) {
            /* hic sunt ponies */
        },
    ),
),
Run Code Online (Sandbox Code Playgroud)

不幸的是, 问题 告诉我,为什么这个错误发生,但不知道如何解决它.

我如何重做这个和类似的,factories以便缓存将与他们一起工作?

net*_*iul 11

将工厂关闭返工到工厂类.

配置

'service_manager' => array(
    'factories' => array(
        'auth.service' => \Fully\Qualified\NS\AuthFactory::class,
    ),
),
Run Code Online (Sandbox Code Playgroud)

namespace Fully\Qualified\NS;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class AuthFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator) {
        // create your object and set dependencies
        return $object
    }
}
Run Code Online (Sandbox Code Playgroud)

除了这种使缓存成为可能的方法之外,另一个优点是PHP将更快地解析您的配置,因为它不必为每个匿名函数的每个请求创建一个Closure类.