Re: Usage of class constants inside strings and heredocs [message #170513 is a reply to message #170510] |
Fri, 05 November 2010 08:41 |
Giuseppe Sacco
Messages: 5 Registered: November 2010
Karma:
|
Junior Member |
|
|
Hi all,
it seems none of these methods are really good (that's my opinion, of
course) when used in my scenario. I'll try to better depict what is my
source architecture in order to better explain the problem.
I have a few classes that should be used for accessing postgresql
database. The classes are a super class called Table and a few derived
classes, one for each table. The superclass provide methods for
creating insert and update statements. These statements are stored
into the database connection via pg_prepare(). Other Table method will
receive a record and actually call pg_execute() on the prepared
statement.
The super class will use reflection on $this for getting all field
names (declared as class constants) and prepare its statement.
Something similar to this:
class Table {
/*
* Create an SQL statement for pg_prepare()
*/
public function CreaInsertStatement() {
$fields = "";
$values = "";
$j = 1;
$c = new ReflectionClass(get_class($this));
foreach ($c->getConstants() as $key => $value) {
if ($j == 1) {
$fields = "$value";
$values = "\$1";
}
else {
$fields .= ",$value";
$values .= ",\$$j";
}
$j++;
}
$sql = "INSERT INTO {$this->nometabella} (${fields}) VALUES ($
{values})";
return $sql;
}
/*
* Take a record with only data and create a new array with
* all fields ordered as in CreaInsertStatement.
* The final array is to be used in pg_execute()
*/
public function ConvertiArrayPerInsert($assoc)
{
$v = array();
$j = 0;
$c = new ReflectionClass(get_class($this));
foreach ($c->getConstants() as $key => $value) {
$valore = $assoc[$value];
if (is_object($valore)) {
$classe = get_class($valore);
if ("DateTime" == $classe) {
// convert DateTime into string (TimeStamp) since pg_execute
// wouldn't convert it
/* @var $valore DateTime */
$valore = $valore->format('Y-m-d H:i:s');
}
}
$v[$j++] = $valore;
}
return $v;
}
} // end Table class
class Anagrafica extends Tabella {
// elenco dei campi nel database
const DB_ANAG_COD_ANAG = "cod_anag";
const DB_ANAG_COD_ORIGINALE = "cod_originale";
const DB_ANAG_COD_TIPOANAGRAFICA = "cod_tipoanagrafica";
const DB_ANAG_COD_FONTE = "cod_fonte";
const DB_ANAG_COD_TIPORAPPORTO = "cod_tiporapporto";
// more fields ....
protected $primarykey = array(
Anagrafica::DB_ANAG_COD_ANAG => Anagrafica::DB_ANAG_COD_ANAG,
Anagrafica::DB_ANAG_COD_ORIGINALE =>
Anagrafica::DB_ANAG_COD_ORIGINALE);
protected $nometabella = "anagrafica";
}
Thanks again,
Giuseppe
|
|
|