PHP and Zend framework
6 answers
You can use the doctrine2 Doctrine project . There is a ZF3 DoctrineModule compatible module . You can use QueryBuilder which brings query creation to object manipulation.
+1
source to share
1.Config:
config / autoload / dbAdapter.local.php
<?php
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=name;host=localhost',
'username' => 'root',
'password' => 'root',
),
'service_manager' => array(
'abstract_factories' => array(
'Zend\Db\Adapter\AdapterAbstractServiceFactory',
),
),
);
- Implementation:
public function testAction()
{
$username = 'user';
$sql = "SELECT email FROM users WHERE username = ?";
$statement = $this->getDbAdapter()->createStatement($sql, array($username));
$result = $statement->execute()->current();
}
protected function getDbAdapter()
{
if($this->dbAdapter == null) {
$this->dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
}
return $this->dbAdapter;
}
0
source to share
The Zend framework has abstract_factories, it allows you to handle multiple database queries:
Zend \ Db \ adapter \ AdapterAbstractServiceFactory
-
Service Manager needs to be installed:
'service_manager' => array ('abstract_factories' => array ('Zend \ Db \ adapter \ AdapterAbstractServiceFactory',),),
-
Configuring adapters in config / autoload / local.php
db '=> array (' adapters' => array (
'database1' => array( 'driver' => 'Pdo', 'dsn' => 'mysql:dbname=userDB;host=localhost', 'driver_options' => array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'' ), ), etc... ),
),
-
Configuring adapters in config / autoload / global.php
return array( 'db' => array( 'adapters' => array( 'database1' => array( 'username' => 'root', 'password' => '', ), ), ),
);
-
Call adapters
$ dbmanager-> Get ('Database1');
-
Use in the model
use Zend\Db\TableGateway\AbstractTableGateway; use Zend\Db\Adapter\Adapter; class UserTable extends AbstractTableGateway { protected $table ='user'; public function __invoke(Adapter $adapter) { $this->adapter = $adapter; $this->initialize(); } public function fetchAll() { $resultSet = $this->select(); return $resultSet->toArray(); }
}
0
source to share