6

我知道這已被其他線程廣泛覆蓋,但我正在努力研究如何在ZF3中從ZF2控制器複製$ this-> getServiceLocator()的效果。ZF3服務管理器

我試着創建一個工廠,使用我在這裏和其他地方找到的各種其他答案和教程,但最終陷入了與他們每個人的混亂中,所以我粘貼我的代碼,因爲它是當我開始希望有人能指引我正確的方向?

從/module/Application/config/module.config.php

'controllers' => [ 
    'factories' => [ 
     Controller\IndexController::class => InvokableFactory::class, 
    ], 
], 

從/module/Application/src/Controller/IndexController.php

public function __construct() { 
    $this->objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); 
    $this->trust = new Trust; 
} 

回答

11

You can not use $this->getServiceLocator() in controller any more

你應該添加一個類IndexControllerFactory在那裏你會得到的依賴性和在IndexController中注入它

首先重構你的配置:

'controllers' => [ 
    'factories' => [ 
     Controller\IndexController::class => Controller\IndexControllerFactory::class, 
    ], 
], 

不是創建IndexControllerFactory.php

<?php 

namespace ModuleName\Controller; 

use ModuleName\Controller\IndexController; 
use Interop\Container\ContainerInterface; 
use Zend\ServiceManager\Factory\FactoryInterface; 

class IndexControllerFactory implements FactoryInterface 
{ 
    public function __invoke(ContainerInterface $container,$requestedName, array $options = null) 
    { 
     return new IndexController(
      $container->get(\Doctrine\ORM\EntityManager::class) 
     ); 
    } 
} 

在最後重構你索引控制器來獲得依賴關係

public function __construct(\Doctrine\ORM\EntityManager $object) { 
    $this->objectManager = $object; 
    $this->trust = new Trust; 
} 

您應該檢查的官方文檔zend-servicemanager和周圍有點玩...

+0

謝謝!這是我犯了一個錯誤的配置。 –

+0

不錯的例子!考慮到每個控制器有多個操作,但每個控制器都有一個工廠。如果您在不使用其他特定操作的情況下使用對象,則您正在初始化相同案例中的額外對象。這個案子應該是什麼解決方案? –

+0

簡單:)爲每個控制器創建一個動作。事實上,現在的趨勢是微型框架和PHP中間件...... – tasmaniski