Last active
May 16, 2021 04:50
-
-
Save nadalizadeh/99e37432daa2579e8ce43de5113dac76 to your computer and use it in GitHub Desktop.
SELECT....FOR UPDATE hack in Zend Framework 2 (ZF2)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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