0

私のアプリはデータ マッパー パターンを使用しているため、多数のマッパー クラスがあり、それぞれがデータベース アダプターのインスタンスを必要とします。したがって、factories私のサービス構成のセクションには、次のようなエントリが含まれています。

'UserMapper' => function($sm) {
    $mapper = new UserMapper();
    $adapter = $sm->get('Zend\Db\Adapter\Adapter');
    $mapper->setAdapter($adapter);

    return $mapper;
},
'GroupMapper' => function($sm) {
    $mapper = new GroupMapper();
    $adapter = $sm->get('Zend\Db\Adapter\Adapter');
    $mapper->setAdapter($adapter);

    return $mapper;
},

この定型コードの一部を削除したいと思います。これらのマッパー専用のカスタム サービス ロケーター クラスを定義することは可能ですか? カスタム ファクトリ構成で定義が存在しない限り、DB アダプターを提供することで任意のマッパー クラスをインスタンス化できますか?

4

1 に答える 1

4

これには 2 つの方法があります。

1 つ目は、マッパーに を実装Zend\Db\Adapter\AdapterAwareInterfaceさせ、インターフェースを実装するサービスにアダプターを挿入するサービス マネージャーにイニシャライザーを追加することです。invokablesこれを行うと、それぞれのファクトリを必要とする代わりに、すべてのマッパーをサービス構成のキーに配置できます。

すべてのマッパーは次のようになります

<?php
namespace Foo\Mapper;

use Zend\Db\Adapter\Adapter;
use Zend\Db\Adapter\AdapterAwareInterface;
// if you're using php5.4 you can also make use of the trait
// use Zend\Db\Adapter\AdapterAwareTrait;

class BarMapper implements AdapterAwareInterface;
{
    // use AdapterAwareTrait;

    // ..
    /**
     * @var Adapter
     */
    protected $adapter = null;

    /**
     * Set db adapter
     *
     * @param Adapter $adapter
     * @return mixed
     */
    public function setDbAdapter(Adapter $adapter)
    {
        $this->adapter = $adapter;

        return $this;
    }

}

サービス マネージャー構成で、マッパーを invokables の下に配置し、AdapterAware サービスの初期化子を追加します。

return array(
   'invokables' => array(
       // ..
       'Foo/Mapper/Bar' => 'Foo/Mapper/BarMapper',
       // ..
    ),
    'initializers' => array(
        'Zend\Db\Adapter' => function($instance, $sm) {
            if ($instance instanceof \Zend\Db\Adapter\AdapterAwareInterface) {
                $instance->setDbAdapter($sm->get('Zend\Db\Adapter\Adapter'));
            }
        },
    ),
);

別の方法は、 を作成することです。MapperAbstractServiceFactoryこの回答 -> ZF2 依存性注入 in 親は、その方法を説明しています。

于 2013-05-14T09:14:25.853 に答える