Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitkorn/083bbd4f36c7c40c1f9826401d2f1e4c to your computer and use it in GitHub Desktop.
Save bitkorn/083bbd4f36c7c40c1f9826401d2f1e4c to your computer and use it in GitHub Desktop.
ZF2 log SQL string with driver-support
<?php
namespace BitkornShop\Table\Basket;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\HydratingResultSet;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\AdapterAwareInterface;
/**
*
* @author allapow
*/
class SomeTable extends AbstractTableGateway implements AdapterAwareInterface
{
/**
*
* @var string
*/
protected $table = 'table_name';
/**
*
* @var \Zend\Log\Logger
*/
protected $logger;
public function setDbAdapter(Adapter $adapter)
{
$this->adapter = $adapter;
$this->resultSetPrototype = new HydratingResultSet();
$this->initialize();
}
public function setLogger(\Zend\Log\Logger $logger)
{
$this->logger = $logger;
}
protected function log(\Exception $ex)
{
$this->logger->err($ex->getMessage());
$this->logger->err($ex->getFile() . ' at line: ' . $ex->getLine());
}
/**
*
* @return array
*/
public function getSomeFromDb()
{
$select = $this->sql->select();
try {
/*
* Log the SQL string.
* Sometimes in complex queries we need to quote else the following throws:
* Notice: Attempting to quote a value without specific driver level support can introduce security vulnerabilities in a production environment.
* in /var/www/html/systemgurt/vendor/zendframework/zend-db/src/Adapter/Platform/Sql92.php on line 29
*/
$this->logger->debug($select->getSqlString($this->adapter->getPlatform()));
$resultset = $this->selectWith($select);
if ($resultset->valid() && $resultset->count() > 0) {
return $resultset->toArray();
}
} catch (\RuntimeException $ex) {
$this->log($ex);
}
return [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment