Zend Framework 2 TableGateway

时间:2013-07-17 10:07:01

标签: php zend-framework2

除了使用构造函数注入之外,还有另一种设置DbAdapterTableGateway表名的方法吗?

我通过扩展下面的AbstractTableGateway类来实现它,但我想将这个逻辑移到顶层配置并摆脱它,因为它是不必要的。

namespace Application\Repository;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\AdapterAwareInterface;
use Zend\Db\Adapter\Adapter;

abstract class AbstractRepository extends AbstractTableGateway implements AdapterAwareInterface
{
    public function setDbAdapter(Adapter $adapter) {
        $this->table   = preg_replace('/.*\\\([a-zA-Z]+)Repository/', '$1', get_class($this));
        $this->table   = strtolower($this->table);
        $this->adapter = $adapter;
        $this->initialize();
    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用服务工厂来完成此任务(不是一个完美的例子,我的使用原则,但它可以很容易地适应您的需要):

https://gist.github.com/Spabby/6019494

答案 1 :(得分:0)

您可以使用DI。

'di' => array (
    'instance' => array (
        'Transifex\Gateway\Language' => array (
            'parameter' => array (
                'table' => 'translations_language',
                'adapter' => 'Zend\Db\Adapter\Adapter'
            )
        ),
    ),
),

'service_manager' => array (
    'factories' => array (
        'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory'
    )
),

'db' => array (
    'driver' => 'mysqli',
    'params' => array (
        'host' => 'something.dev',
        'port' => '3306',
        'user' => 'john',
        'password' => 'secret',
        'dbname' => 'primary'
    )
)

然后在控制器中:

$this->getServiceLocator ()->get ('Transifex\Gateway\Language');