php - ZF2 - ServiceManager 和 'aware' 接口(interface)

标签 php zend-framework2

第一个 ZF2 应用程序,已经实现了,但我认为在依赖注入(inject)和 ServiceManager 方面仍然缺少一两个思考。

我目前正在编写的新数据库网关类遇到一个特殊问题。我不会注入(inject)数据库适配器,所以我实现了 AdapterAwareInterface。但我的类中从未调用 setDbAdapter 方法。我想知道是否有人会好心地查看我的代码并提出可能出现问题的地方(或者我遗漏的地方!)。

所以,这是我实现 AdapterAwareInterface 的类。

<?php
namespace Foo\Database;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Adapter\AdapterAwareInterface;
use Zend\Log\LoggerAwareInterface;
use Zend\Log\LoggerInterface;


class Gateway implements AdapterAwareInterface, LoggerAwareInterface
{
protected $logger = NULL;
protected $db = NULL;

public function setDbAdapter(Adapter $adapter)
{
    $this->db = $adapter;
} 

public function setLogger(LoggerInterface $logger)
{
    $this->logger = $logger;
}

这是我的模块文件的摘录,显示了我如何配置服务管理器:

    public function getServiceConfig()
{
    return array(
        'factories' => array(
          ....
        ),
        'invokables' => array(
            'FooDatabaseGateway' => 'Foo\Database\Gateway',
        ),
        'abstract_factories' => array(
            'AbstractFeedParserFactory' => 'Bookmakers\Odds\Feeds\AbstractFeedParserFactory',
        ),
    );
}

这就是我测试的方式:

gateway = $this->getServiceLocator()->get('FooDatabaseGateway');

这是我的全局配置的一部分:

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

非常感谢您提供的任何帮助。

:wq

最佳答案

好吧,今天早上我们对这个问题有了新的认识。我认为这是写的答案..至少这就是说它对我有用。如果有人想建议一种完全不同的更好的方法,那么请这样做:-)。

所以缺少的一点是使用 initializer在我的服务管理器配置中调用 setDbAdapter函数在任何实现 AdapterAwareInterface 的类实例上。所以在数组中我从 getServiceConfig 返回在我的Module.php文件中,我添加了以下条目:

public function getServiceConfig() {
  return array(
    'initializers' => array(
      'db' => function($service, $sm)
      {
        if ($service instanceof AdapterAwareInterface)
        {
          $service->setDbAdapter($sm->get('Zend\Db\Adapter\Adapter'));
        }
      }....

我认为在学习 ZF2 时我缺少的是有很多构建 block 可以使用,但你必须自己将它们组合在一起。

事情看起来不错,我很喜欢这个框架,但是还有很多东西需要学习,而且我仍然不相信使用服务器管理器注入(inject)而不是好的旧构造函数注入(inject)!

:wq

关于php - ZF2 - ServiceManager 和 'aware' 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13807884/

相关文章:

zend-framework2 - 设置 ZF2 中的 (404) 错误页面使用的布局变量

php - php 不接受所有图像扩展名?

php - 从 'submit' 按钮在 PHP 中插入 mysql 值无法按预期工作

php 帮助从查询中获取 id

PHP:检查字符串是否包含不在数组中的字符

zend-framework2 - ZF2。我是否总是需要从操作中返回 ViewModel?

php - 如何在 HostGator 上使用 PHP Composer

zend-framework2 - MasterSlaveFeature 操作方法

php - Zend Framework 2 - 如何使前端和后端的 View 分离?

PHP:foreach 循环与 array_merge 来创建 json 对象