1

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

我通过扩展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();
    }
}
4

2 回答 2

0

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

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

于 2013-07-17T10:38:53.813 回答
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');
于 2013-07-18T09:33:52.907 回答