简体   繁体   English

Zend Framework 2 TableGateway

[英]Zend Framework 2 TableGateway

is there another way to set DbAdapter and table name for TableGateway besides using constructor injection? 除了使用构造函数注入之外,还有另一种方法可以为TableGateway设置DbAdapter和表名吗?

I achieved it by extending AbstractTableGateway class below but I want to move this logic somewhere to the top-level configuration and get rid of it because it's needless. 我是通过在下面扩展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();
    }
}

You can use a service factory to accomplish this (not a perfect example, mine uses doctrine, but it can easily be adapted for your needs): 您可以使用服务工厂来完成此操作(这不是一个完美的例子,我使用的是理论,但可以轻松地将其适应您的需求):

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

You could employ the DI. 您可以雇用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'
    )
)

and then in a controller: 然后在控制器中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM