在 ZF2 服务中实现 ServiceLocatorAwareInterface 依赖项,用于 forward() 类


Implementing ServiceLocatorAwareInterface dependency for forward() class in a ZF2 service

已编辑(代码已更新并适用于其他人)
对于正在发生的事情的整体想法。

我正在尝试从控制器中的视图访问帖子数据,而无需刷新页面。

为此,我通过使用 ViewHelper 调用下面的服务来执行页面控制器,然后转发回控制器;之后,我可以在页面控制器中管理发布的数据。

除了最后一步是forward()之外,一切都有效,我收到错误调用未定义的方法AlbumModule'Service'postAlbumService::forward()

我知道我必须实现ServiceLocatorAwareInterface才能使用 forward() 类,但我编写的内容似乎不起作用。

            <?php
            namespace AlbumModule'Service;
            use Zend'ServiceManager'ServiceLocatorAwareInterface;
            use Zend'ServiceManager'ServiceLocatorInterface;
            class postAlbumService implements
                ServiceLocatorAwareInterface
            {
                protected $services;
                public function __construct() {
                    echo '<script>console.log("postAlbumService is Started")</script>';
                }
                public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
                {
                    $this->services = $serviceLocator;
                }
                public function getServiceLocator()
                {
                    return $this->services;
                }
                public function test(){
                    $cpm = $this->getServiceLocator()->get('controllerpluginmanager');
                    $fwd = $cpm->get('forward');
                    echo '<script>console.log("postAlbumService TEST() is Started")</script>';
                    return $fwd->dispatch('newAlbum', array('action' => 'submitAlbum'));
                }
            }

似乎我只是对 forward() 类有依赖问题,但我不确定问题是什么。

编辑-
这是我如何从视图助手调用postAlbumService

            <?php
            namespace AlbumModule'View'Helper;
            use Zend'View'Helper'AbstractHelper;
            class invokeIndexAction extends AbstractHelper
            {
             protected $sm;
                   public function test()
                    {
                        $this->sm->getServiceLocator()->get('AlbumModule'Service'postAlbumService')->test();
                    }
                    public function __construct($sm) {
                        $this->sm = $sm;
                    }
            }
在将

依赖项注入服务后,有没有办法调用所请求的服务中的特定类?

你做错了几件事,你误解了一些事情......

首先,forward()是一个控制器插件。您可以通过服务定位器访问所述管理器来访问此方法。一个例子可能是这样的:

$cpm = $serviceLocator->get('controllerpluginmanager');
$fwd = $cpm->get('forward');
return $fwd->dispatch('foo/bar');

现在,要将服务定位器放入任何服务类中,您需要依赖注入。方法之一是 实施ServiceLocatorAwareInterface .ZF2 的服务管理器具有所谓的侦听器。这些侦听器检查实现的接口和类似的东西。每当它找到匹配项时,它都会通过给定函数的接口注入所需的依赖项。工作流如下所示:

ServiceManager get('FooBar');
    $ret = new FooBar();
    foreach (Listener) 
        if $ret instanceof Listener
             doInjectDependenciesInto($ret)
        end
    end
    return $ret

现在这告诉你什么。这告诉您,在任何类的__construct()中,实际上没有一个所需的依赖项。它们只有在类/服务实例化后才会被注入。

最后一点,给定的代码示例并没有多大意义;)无论我想访问什么服务操作,您总是会让我返回到"新相册"操作......