0

テーブルモデルでデフォルトのdbadabterを取得するにはどうすればよいですか?トランザクションの作成に使用したいと思います。

database.global.php内:

    return array(
   'service_manager' => array(
        'factories' => array(
            'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
        ),
        'aliases' => array(
            'db' => 'Zend\Db\Adapter\Adapter',
        ),
    ),
    'db' => array(
        'driver'         => 'Pdo',
        'dsn'            => 'mysql:dbname=cww;host=localhost',
        'driver_options' => array(
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
        ),
    ),
);

$this->adapter、私は私のalbumTable.phpに入れたいです

私はそれを次のように受け取ろうとしました:

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Expression;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Update;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;
use Ajax\Model\Album;

class AlbumTable implements ServiceLocatorAwareInterface
{
    protected $tableGateway;
    protected $adapter;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
        $this->adapter  = $this->getServiceLocator()->get('db');    
    }

しかし、エラーが発生します:

致命的なエラー:クラスAjax \ Model \ AlbumTableには2つの抽象メソッドが含まれているため、抽象として宣言するか、残りのメソッド(Zend \ ServiceManager \ ServiceLocatorAwareInterface :: setServiceLocator、Zend \ ServiceManager \ ServiceLocatorAwareInterface :: getServiceLocator)を実装する必要があります。

4

2 に答える 2

1

次の関数を追加します。

public function getServiceLocator() {
    return $this->serviceLocator;
}


public function setServiceLocator(Zend\ServiceManager\ServiceLocatorInterface $serviceLocator) {
    $this->serviceLocator= $serviceLocator;
    return $this;
}

次に、次のことができます。

$this->$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');

ただし、入門ガイドTableGatewaysを読むと、サービス マネージャー ファクトリを使用して構築し、DbAdapter とその他のパラメーターを次のように渡す方法が説明されています。

'RoleTableGateway' => function ($sm) {
    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
    $resultSetPrototype = new ResultSet();
    $resultSetPrototype->setArrayObjectPrototype(new Role());
    return new TableGateway('role', $dbAdapter, null, $resultSetPrototype);
},
于 2013-03-14T16:10:52.383 に答える
0

これを使用してデータベース アダプタを作成します。

$adapter = $this->getServiceLocator()->get('db');

エイリアスを作成した場合にのみ「db」を使用できます。また、\autoload\config\local.php の locals.php に何か書いてみることもできます。ここで、mySQL でデータベース クエリを実行するとします。SQL ステートメントを作成し、変数 $sql に入れます。今これを行います:

$statement = $adapter->createStatement($sql);
$result = $statement->execute();

お役に立てれば。

于 2014-10-10T07:54:48.230 に答える