Skip to content

Instantly share code, notes, and snippets.

@nadalizadeh
Last active May 16, 2021 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nadalizadeh/99e37432daa2579e8ce43de5113dac76 to your computer and use it in GitHub Desktop.
Save nadalizadeh/99e37432daa2579e8ce43de5113dac76 to your computer and use it in GitHub Desktop.
SELECT....FOR UPDATE hack in Zend Framework 2 (ZF2)
<?php
/* Adjust namespace with your own code */
namespace Data;
use Zend\Db\Adapter\Driver\DriverInterface;
use Zend\Db\Adapter\ParameterContainer;
use Zend\Db\Adapter\Platform\PlatformInterface;
use Zend\Db\Sql\Platform\Mysql\SelectDecorator;
class CustomSelectDecorator extends SelectDecorator {
/* Set this flag to add FOR UPDATE at the end of statement */
protected $forupdate = null;
/* override processStatementEnd */
protected function processStatementEnd(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null)
{
$theString = parent::processStatementEnd($platform, $driver, $parameterContainer);
if ($this->forupdate)
$theString .= "$theString FOR UPDATE";
return $theString;
}
}
<?php
use Data\CustomSelectDecorator;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Where;
use Zend\Db\TableGateway\TableGateway;
class SampleDatabaseObjectModel {
public $tableGateway;
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
}
/**
* @param int $id
* @return Model|null
*/
public function find($id) {
$theSQL = $this->tableGateway->getSql();
$theSQL->getSqlPlatform()->setTypeDecorator('Zend\Db\Sql\Select', new CustomSelectDecorator());
$rowset = $this->tableGateway->select(function (Select $select) use ($id) {
$select->where(array('id' => $id));
$select->forupdate = true;
});
return $rowset->current();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment