0

モデルの作成からテーブルの操作の管理については、Zend Framework 2 のマニュアルを参照しました。メソッド exchangeArray() を持つクラスは必要ですか? データのコピーのみです:/ いくつかのテーブルを管理するために 1 つのモデルを作成できますか?

2 つのクラスを作成しました。

namespace Application\Model;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Adapter\AdapterAwareInterface;

    abstract class AbstractAdapterAware implements AdapterAwareInterface
    {
        protected $db;

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

と:

namespace Application\Model;

class ExampleModel extends AbstractAdapterAware
{

    public function fetchAllStudents()
    {

        $result = $this->db->query('select * from Student')->execute();

        return $result;
    }

}

Module.php にもエントリを追加します。

'initializers' => [
                'Application\Model\Initializer' => function($instance, \Zend\ServiceManager\ServiceLocatorInterface $serviceLocator){
                    if ($instance instanceof AdapterAwareInterface)
                    {
                        $instance->setDbAdapter($serviceLocator->get('Zend\Db\Adapter\Adapter'));
                    }
                }

            ],
    'invokables' => [
        'ExampleModel' => 'Application\Model\ExampleModel'
    ],

次の方法でモデルからメソッドを実行します。

$this->getServiceLocator()->get('ExampleModel')->fetchAllStudents();
4

1 に答える 1

0

コードで 2 つのことを行う必要があります。まず、AdapterAwareInterface を適切に実装します。次に、アダプタをモデルに挿入するイニシャライザを作成します。以下のコードを検討してください。

...

'initializers' => [
    function($instance, ServiceLocatorInterface $serviceLocator){
            if ($instance instanceof AdapterAwareInterface) {
                $instance->setDbAdapter($serviceLocator->get('Zend\Db\Adapter\Adapter'));
            }
    }
]

...

abstract class AbstractModel implements AdapterAwareInterface
{
    protected $db;

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

...

'invokables' => [
    'ExampleModel' => 'Application\Model\ExampleModel'
]

上からわかるように、結局のところ、モデルごとにファクトリは必要ありません。呼び出し可能オブジェクトを登録するか、Abstract Factory を作成してモデルをインスタンス化できます。以下の例を参照してください。

...

'abstract_factories' => [
    'Application\Model\AbstractFactory'
]

...

class AbstractFactory implements AbstractFactoryInterface
{
    public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
    {
        return class_exists('Application\Model\'.$requestedName);
    }

    public function createServiceWithName(\Zend\ServiceManager\ServiceLocatorInterface $serviceLocator, $name, $requestedName)
    {
        $class = 'Application\Model\'.$requestedName();

        return new $class
    }
}

お役に立てれば

于 2014-10-22T06:19:51.573 に答える