11

viewhelperでアクセスできるzf2で簡単なサービスを作成しようとしています

ステップ1。私は次のようにsrc/Application / Service/Service1.phpのクラスを作成しました

namespace Application\Service;
    use Zend\ServiceManager\ServiceLocatorAwareInterface;
    use Zend\ServiceManager\ServiceLocatorInterface;

    class Service1 implements ServiceLocatorAwareInterface
    {

        public function __construct()
        {

        }

        public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
        {

        }    

        public function getServiceLocator()
        {

        }

    }

ステップ2これをmodule.phpファイルで次のように設定します。

public function getServiceConfig()
{    
     return array(
        'factories' => array(
            'Application\Service\Service1' => function ($sm) {
                return new \Application\Service\Service1($sm);
            },
        )
    );   
}

public function onBootstrap($e)
{        
   $serviceManager = $e->getApplication()->getServiceManager();

    $serviceManager->get('viewhelpermanager')->setFactory('Abc', function ($sm) use ($e) {
        return new \Application\View\Helper\Abc($sm); 
    });
}

Step3最後に、このようなビューヘルパーsrc / Application / View / Helper / Abc.php test()メソッドで取得しています。この行$this->sm->get('Application\Service\Service1');にエラーはありません。サービスに不足しているものがあるはずです。

namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;

    class Abc extends AbstractHelper 
    {
       protected $sm;

       public function test()
        {
            $this->sm->get('Application\Service\Service1');
        }
        public function __construct($sm) {
            $this->sm = $sm;

        }
    }

ステップ4次に、このようなビューの1つでテストビューヘルパーを呼び出します。

$this->Abc()->test();

次のエラーが発生します。

Fatal error: Call to undefined method Application\Service\Service1::setView() in vendor/zendframework/zendframework/library/Zend/View/HelperPluginManager.php on line 127 Call Stack:

私は何が欠けていますか?

4

2 に答える 2

7

PHP 5.4のみで、特定の構成を行わない別の方法は、トレイトを使用することです。

module.config.phpの抽出:

'view_helpers' => array(
    'invokables' => array(
        'myHelper' => 'Application\View\Helper\MyHelper',
    ),  

MyHelper.php:

<?php
namespace Application\View\Helper;

use Zend\ServiceManager\ServiceLocatorAwareInterface;  

class HeadScript extends \Zend\View\Helper\MyHelper implements ServiceLocatorAwareInterface
{
    use \Zend\ServiceManager\ServiceLocatorAwareTrait;

    public function __invoke()
    {
        $config = $this->getServiceLocator()->getServiceLocator()->get('Config');
        // do something with retrived config
    }

}
于 2013-02-15T06:35:53.587 に答える
5

$this->sm->getServiceLocator()->get('Application\Service\Service1');以下の方法で行を変更します

class Abc extends AbstractHelper 
{
   protected $sm;

   public function test()
    {
        $this->sm->getServiceLocator()->get('Application\Service\Service1');
    }
    public function __construct($sm) {
        $this->sm = $sm;

    }
}
于 2012-09-24T11:36:33.177 に答える