简体   繁体   中英

Zend Framework 2 TableGateway

is there another way to set DbAdapter and table name for TableGateway besides using constructor injection?

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.

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

You could employ the 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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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