AbstractTableGateway

Zend\Db\TableGateway\AbstractTableGateway

 

A classe AbstractTableGateway vem para criar uma segunda camada na conversa do programador com uma tabela de banco de dados. Essa classe possui um objeto interno da classe Sql e é encima dele que tudo é trabalhado.
A Segunda Camada

 

Um instância da classe Sql pode ser vista como um representante de uma tabela qualquer, onde posso capturar um objeto select, por exemplo, trabalhar os dados da minha busca nele, retornar o objeto à classe e receber um statement para executar.
O AbstractTableGateway criar uma segunda camada, onde, dependendo das circunstâncias, não precisariamos pegar um objeto Insert para passar minhas vontades a ele, pegar o statement dele e executar, mas já passar minhas vontades diretamente a um método para criá-lo, pegar o statement e executar.
Veja dois exemplos de uma simples busca no banco de dados:

 

$sql ligada à tabela ‘produto’
$select = $sql->select();
$select->where(array(‘id’ => 1));
$statement  = $select->prepareStatementForSqlObject($select);
$statement->execute();

 

AbstractTableGateway ligado à tabela ‘produto’
$abstractTableGateway->select(array(‘id’ => 1));
O que o método select() do AbstractTableGateway faz internamente é exatamente o que fizemos manualmente, veja:

 

/**
    * Select
    *
    * @param Where|\Closure|string|array $where
    * @return ResultSet
    */
   public function select($where = null)
   {
       if (!$this->isInitialized) {
           $this->initialize();
       }
       $select = $this->sql->select();
       if ($where instanceof \Closure) {
           $where($select);
       } elseif ($where !== null) {
           $select->where($where);
       }
       return $this->selectWith($select);
   }
   /**
    * @param Select $select
    * @return null|ResultSetInterface
    * @throws \RuntimeException
    */
   public function selectWith(Select $select)
   {
       if (!$this->isInitialized) {
           $this->initialize();
       }
       return $this->executeSelect($select);
   }
   /**
    * @param Select $select
    * @return ResultSet
    * @throws \RuntimeException
    */
   protected function executeSelect(Select $select)
   {
       $selectState = $select->getRawState();
       if ($selectState[‘table’] != $this->table) {
           throw new \RuntimeException(‘The table name of the provided select object must match that of the table’);
       }
       if ($selectState[‘columns’] == array(Select::SQL_STAR)
           && $this->columns !== array()) {
           $select->columns($this->columns);
       }
       // apply preSelect features
       $this->featureSet->apply(‘preSelect’, array($select));
       // prepare and execute
       $statement = $this->sql->prepareStatementForSqlObject($select);
       $result = $statement->execute();
       // build result set
       $resultSet = clone $this->resultSetPrototype;
       $resultSet->initialize($result);
       // apply postSelect features
       $this->featureSet->apply(‘postSelect’, array($statement, $result, $resultSet));
       return $resultSet;
   }
O método initialize()
Tudo gira em torno do objeto Sql já existente e criada e sempre verificada no método initialize(). Veja alguns trechos do código do método:


/**
    * Initialize
    *
    * @throws Exception\RuntimeException
    * @return null
    */
   public function initialize()
   {
       if ($this->isInitialized) {
           return;
       }
       if (!$this->adapter instanceof AdapterInterface) {
           throw new Exception\RuntimeException(‘This table does not have an Adapter setup’);
       }
       if (!is_string($this->table) && !$this->table instanceof TableIdentifier) {
           throw new Exception\RuntimeException(‘This table object does not have a valid table set.’);
       }
       if (!$this->sql instanceof Sql) {
           $this->sql = new Sql($this->adapter, $this->table);
       }
       $this->isInitialized = true;
   }
Observe a necessidade de haver o nome da tabela no atributo $table e o adapter corretamente inserido no atributo $adapter. Por isso, toda ver que formos trabalhar com algo relacionado a essa classe, devemos satisfazer esses dois quesitos: inserir o nome da tabela ao atributo $table e inserir o adapter no atributo $adapter.

 

Criando um Model
Quando formos criar nosso Model herdando de AbstractTableGatway, devemos sobrescrever o atributo $table passando o nome da tabela e exigir no construtor o adapter.

 

namespace Application\Model;
use \Zend\Db\TableGateway\AbstractTableGateway;
use \Zend\Db\Adapter\Adapter;
class Produto extends AbstractTableGateway
{
   /**
    * @var string
    */
   protected $table = “produto”;
   public function __construct(Adapter $adapter)
   {
       $this->adapter = $adapter;
       $this->initialize();
   }
Sendo assim, estaremos satisfazendo as necessidade do método initilize() visto anteriormente e permitindo que o AbstractTableGateway realize seu papel.

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair /  Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair /  Alterar )

Conectando a %s