0

我浏览了 Zend Framework 2 关于创建模型以管理表上的操作的手册。具有方法 exchangeArray() 的类是必要的吗?它只是复制数据:/我可以创建一个模型来管理几个表吗?

我创建了两个类:

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

你应该用你的代码做两件事。首先,正确实现 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_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 回答