0

我正在學習ZF2。如何使用getServiceLocator()獲取模型中的適配器?

我可以使用getServiceLocator()在模型中獲取適配器嗎?

/config/autoload/global.php

return array(
    'db' => array(
     'driver'   => 'Pdo', 
     'dsn'   => 'mysql:dbname=zf2tutorial;host=localhost', 
     'driver_options' => array(
      PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'' 
     ), 
    ), 
    'service_manager' => array(
     'factories' => array(
      'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory', 
     ), 
     'aliases' => array(
      'db' => 'Zend\Db\Adapter\Adapter', 
     ), 
    ), 
); 

/config/autoload/local.php

return array(
    'db' => array(
     'username' => 'YOUR USERNAME HERE', 
     'password' => 'YOUR PASSWORD HERE', 
    ), 
); 

所以,我怎麼能使用:

$sm = $this->getServiceLocator(); 
$this->dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); 

在模型中獲取適配器?

回答

0

如果您使用的是最新的Zend Framework版本,則不能在控制器類中使用getServiceLocator方法,因爲ServiceLocatorAwareInterfaceServiceManagerAwareInterface都被刪除。

所以這行:你也許在你的控制器類預期

$sm = $this->getServiceLocator(); 

將無法​​工作。


您還可以在the migration guide閱讀更多的這種變化:

以下接口,特點和類被拆除:

  • ...
  • 的Zend \的ServiceManager \ ServiceLocatorAwareInterface
  • Zend \ ServiceManager \ ServiceLocatorAwareTrait
  • 的Zend \的ServiceManager \ ServiceManagerAwareInterface

的ServiceLocatorAware和ServiceManagerAware接口和性狀進行了下V2太經常被濫用,並且代表的服務管理器組件的用途的對立面;依賴關係應該直接注入,並且容器不應該由對象組成。

您將需要重構您的服務,可能最好的方法是創建一個服務工廠,在其中注入您的依賴關係。

檢查this blog post(章節工廠)關於如何建立工廠的更多細節。

2

您將需要在模型創建時將適配器注入到模型中,例如使用工廠。

例如在你的配置:

'service_manager' => array(
    'factories' => array( 
     'Application\Some\Model' => '\Application\Some\ModelFactory' 
    ) 
) 

你會再建立工廠,這將注入適配器插入你的模型:

<?php 
namespace Application\Some; 

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

class ModelFactory implements FactoryInterface 
{ 
    /** 
    * Create service 
    * 
    * @param ServiceLocatorInterface $serviceLocator 
    * @return mixed 
    */ 
    public function createService(ServiceLocatorInterface $serviceLocator) 
    { 
     $adapter = $serviceLocator->get('Zend\Db\Adapter\Adapter'); 

     return new Model($adapter); 
    } 
} 

這樣,你會顯然需要讓你的模型接受在這種情況下,它是構造函數中的適配器。

現在在任何你需要得到你的模型的實例與注入你會打電話適配器:

$serviceLocator->get('Application\Some\Model'); 

這將調用工廠,並帶回該模型的完整與適配器。

然後,您可以使用相同的方法將模型注入到需要的任何控制器或服務類中。正如前面的帖子所說,儘量避免直接將服務定位器/服務管理器注入到對象中,而是使用它從工廠類中添加需要的項目(適配器/映射器等)。

相關問題