. */ namespace Doctrine\ORM\Id; use Serializable; use Doctrine\ORM\EntityManager; /** * Represents an ID generator that uses a database sequence. * * @since 2.0 * @author Roman Borschel */ class SequenceGenerator extends AbstractIdGenerator implements Serializable { /** * The allocation size of the sequence. * * @var int */ private $_allocationSize; /** * The name of the sequence. * * @var string */ private $_sequenceName; /** * @var int */ private $_nextValue = 0; /** * @var int|null */ private $_maxValue = null; /** * Initializes a new sequence generator. * * @param string $sequenceName The name of the sequence. * @param integer $allocationSize The allocation size of the sequence. */ public function __construct($sequenceName, $allocationSize) { $this->_sequenceName = $sequenceName; $this->_allocationSize = $allocationSize; } /** * Generates an ID for the given entity. * * @param EntityManager $em * @param object $entity * * @return integer The generated value. * * @override */ public function generate(EntityManager $em, $entity) { if ($this->_maxValue === null || $this->_nextValue == $this->_maxValue) { // Allocate new values $conn = $em->getConnection(); $sql = $conn->getDatabasePlatform()->getSequenceNextValSQL($this->_sequenceName); $this->_nextValue = (int)$conn->fetchColumn($sql); $this->_maxValue = $this->_nextValue + $this->_allocationSize; } return $this->_nextValue++; } /** * Gets the maximum value of the currently allocated bag of values. * * @return integer|null */ public function getCurrentMaxValue() { return $this->_maxValue; } /** * Gets the next value that will be returned by generate(). * * @return integer */ public function getNextValue() { return $this->_nextValue; } /** * @return string */ public function serialize() { return serialize(array( 'allocationSize' => $this->_allocationSize, 'sequenceName' => $this->_sequenceName )); } /** * @param string $serialized * * @return void */ public function unserialize($serialized) { $array = unserialize($serialized); $this->_sequenceName = $array['sequenceName']; $this->_allocationSize = $array['allocationSize']; } }