function __construct(ServiceLocatorInterface $sl, $table, $id = null, $id_column = 'id') { $dbAdapter = $sl->get('Zend\\Db\\Adapter\\Adapter'); $this->id_column = $id_column; $this->id_value = $id; $this->tableGateway = new TableGateway($table, $dbAdapter); if (!empty($this->id_value)) { $rs = $this->tableGateway->select(array($id_column => $id)); if ($rs->count() > 0) { $data = $rs->current(); foreach ($data as $k => $v) { $this->addColumn($k, $v); } } } else { $metadata = new \Zend\Db\Metadata\Metadata($this->tableGateway->adapter); $columns = $metadata->getColumnNames($table); foreach ($columns as $column_name) { $this->addColumn($column_name, null); } } }
/** * Generates PHP files with field names as constants */ public function generateDbConstants() { $metadata = new \Zend\Db\Metadata\Metadata($this->dbAdapter); $schema = $this->dbAdapter->getDriver()->getConnection()->getCurrentSchema(); $tables = $metadata->getTableNames($schema, true); foreach ($tables as $table) { $words = explode('_', $table); $class = 'Db'; foreach ($words as $word) { $word[0] = strtoupper($word[0]); $class = $class . $word; } $filename = __DIR__ . '/../Utils/DbConsts/' . $class . '.php'; if (file_exists($filename)) { unlink($filename); } $writer = new \Zend\Log\Writer\Stream($filename); $writer->setFormatter(new \Zend\Log\Formatter\Simple('%message%')); $logger = new \Zend\Log\Logger(); $logger->addWriter($writer); $logger->info('<?php'); $logger->info(''); $logger->info('namespace Application\\Utils\\DbConsts;'); $logger->info(''); $logger->info("class {$class}"); $logger->info('{'); $logger->info(" const TABLE = '{$table}';"); $columns = $metadata->getColumnNames($table, $schema); foreach ($columns as $column) { $logger->info(vsprintf(" const %s = '%s';", array(strtoupper($column), $column))); } $logger->info(''); $hasConst = ' static public function hasField($field) { if (!is_string($field)) { return false; } $field = strtoupper($field); $reflect = new \\ReflectionClass(__CLASS__); foreach ($reflect->getConstants() as $name => $value) { if (strtoupper($value) === $field) { return true; } }; return false; }'; $logger->info($hasConst); $logger->info('}'); $logger = null; chmod($filename, 0777); } }
/** * Returns columns names * * @todo colocar no cache * * @return array columns */ public function getColumns() { if (!isset($this->_columns)) { $metadata = new \Zend\Db\Metadata\Metadata($this->getTableGateway()->getAdapter()); $this->_columns = $metadata->getColumnNames($this->getTable()); } return $this->_columns; }