1

我有一个ViewHelper并想在以下位置初始化它Module#getViewHelperConfig()

<?php
namespace Search;

use statements...

class Module implements
    ConfigProviderInterface,
    ServiceProviderInterface,
    AutoloaderProviderInterface,
    ViewHelperProviderInterface {

    public function getConfig() ...

    public function getAutoloaderConfig() ...

    public function getServiceConfig() {
        $breakpoint = null;
        try {
            return array (
                'factories' => array(
                    ...
                    'SearchFormCourseSearchForm' => function ($serviceManager) {
                        $cacheService = $serviceManager->get('Cache\Model\CityStorage');
                        $cities = $cacheService->getCities();
                        $searchForm = new Form\CourseSearchForm($cities);
                        return $searchForm;
                    },
                )
            );
        } ...
    }

    public function getViewHelperConfig() {
        $breakpoint = null;
        return array(
            'factories' => array(
                'searhForm' => function($serviceManager) {
                    $helper = new View\Helper\SearchForm(array('render' => true, 'redirect' => false));
                    $helper->setViewTemplate('search/search/search-courses');
                    $searchForm = $serviceManager->get('SearchFormCourseSearchForm');
                    $helper->setSearchForm($searchForm);
                    return $helper;
                }
            )
        );
    }

但是 ZF 没有给我的工厂打电话。相反,它尝试创建一个新SearchFormCourseSearchForm实例:

致命错误:未捕获的异常 'Zend\ServiceManager\Exception\ServiceNotFoundException' 与消息 'Zend\ServiceManager\ServiceManager::get 无法在 /var/www/bar/foo/vendor/zendframework/ 中获取或创建 SearchFormCourseSearchForm 的实例zendframework/library/Zend/ServiceManager/ServiceManager.php 在第 456 行

我应该如何使用从Module#getServiceConfig()创建ViewHelperin 中获得的服务工厂Module#getViewHelperConfig()

4

1 回答 1

2

您需要获取主要的服务定位器。$serviceManageringetViewHelperConfig()是 View Helper 服务定位器。

要获取函数中的主要服务定位器,getViewHelperConfig()请执行以下操作:

$maimSm = $serviceManager->getServiceLocator();

所以:

public function getViewHelperConfig() {
    return array(
        'factories' => array(
            'searhForm' => function($serviceManager) {
                $helper = new View\Helper\SearchForm(array('render' => true, 'redirect' => false));
                $helper->setViewTemplate('search/search/search-courses');
                $maimSm = $serviceManager->getServiceLocator();
                $searchForm = $maimSm->get('SearchFormCourseSearchForm');
                $helper->setSearchForm($searchForm);
                return $helper;
            }
        )
    );
}

有很多帖子更详细地解释了这个策略,我会去寻找它们。

编辑

有关ZF2 中服务管理器/定位器的详细描述,请参阅在应用程序中使用 Zend Framework 服务管理器。

于 2013-04-10T13:15:25.657 回答