我很担心如何在mapper类中注入(Zend / Apigility)一个特定的数据库适配器(这里称为音乐),关于以下映射器:
AlbumMapper.php
<?php
namespace music\V1\Rest\Album;
use Zend\Db\Sql\Select;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Paginator\Adapter\DbSelect;
class AlbumMapper
{
protected $adapter;
public function __construct(AdapterInterface $adapter)
{
$this->adapter = $adapter;
}
public function fetchAll()
{
$select = new Select('album');
$paginatorAdapter = new DbSelect($select, $this->adapter);
$collection = new AlbumCollection($paginatorAdapter);
return $collection;
}
public function fetchOne($id)
{
$sql = 'SELECT * FROM album WHERE id = ?';
$resultset = $this->adapter->query($sql, array($id));
$data = $resultset->toArray();
if (!$data) {
return false;
}
$entity = new AlbumEntity();
$entity->exchangeArray($data[0]);
return $entity;
}
}
Module.php
public function getServiceConfig()
{
return array(
'factories' => array(
'music\V1\Rest\Album\AlbumMapper' => function ($sm) {
$adapter = $sm->get('Zend\Db\Adapter\Adapter');
return new \music\V1\Rest\Album\AlbumMapper($adapter);
},
),
);
}
AlbumResourceFactory.php
<?php
namespace music\V1\Rest\Album;
class AlbumResourceFactory
{
public function __invoke($services)
{
$mapper = $services->get('music\V1\Rest\Album\AlbumMapper');
return new AlbumResource($mapper);
}
}
这将从config / autoload / user.global.php文件中获取数据库适配器凭据,该文件根据此文件注释在生产模式方面不合适。
答案 0 :(得分:0)
我认为正确的解决方案涉及编辑Module.php文件:
public function getServiceConfig()
{
$dbParams = array(
'database' => 'music',
'username' => 'root',
'password' => 'myPassword',
'hostname' => 'localhost',
);
return array(
'factories' => array(
'music\V1\Rest\Album\AlbumMapper' => function ($sm) use ($dbParams) {
$adapter = new \Zend\Db\Adapter\Adapter(array(
'driver' => 'pdo',
'dsn' => 'mysql:dbname='.$dbParams['database'].';host='.$dbParams['hostname'],
'database' => $dbParams['database'],
'username' => $dbParams['username'],
'password' => $dbParams['password'],
'hostname' => $dbParams['hostname'],
));
return new \music\V1\Rest\Album\AlbumMapper($adapter);
},
),
);
}
如果有更好的解决方案,我愿意接受建议,但这很有效。
答案 1 :(得分:0)
您可以使用Zend\Db\Adapter\AdapterServiceFactory
以另一种(推荐)方式执行此操作。
首先在config/autoload/global.php
中配置全局数据库设置,然后配置AdapterServiceFactory
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=music;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter'
=> 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
);
然后您可以覆盖config/autoload/local.php
return array(
'db' => array(
'username' => 'root',
'password' => 'myPassword',
),
);
在Module.php
之后,你可以从'Zend\Db\Adapter\Adapter'
获得ServiceManager
:
public function getServiceConfig()
{
return array(
'factories' => array(
'music\V1\Rest\Album\AlbumMapper' => function ($sm) {
$adapter = $sm->get('Zend\Db\Adapter\Adapter');
return new \music\V1\Rest\Album\AlbumMapper($adapter);
},
),
);
}