Data types: TypeSafeStruct
Tom Schaefer (contact me)
A Case Study for getting PHP type safe.
This package can be used to manipulate type safe objects in a way that works with PHP caching extensions.
It provides base classes that can check whether the types of the values to assign variables of implementation subclasses are of the expected types.
The expected types are determined by the prefixes of private variables, so it works well even when using PHP compiled code cached extensions.
An additional class can serialize objects as XML documents or to insert them in database tables.
The goal of this class is not to replace ORM or other db classes. It shall replace
the stdClass when using mysql_fetch_object.
It returns a value type object for each column. There are a number of value types:
+ TString
+ TNumber
+ TBit
+ TEnum
+ TLob
+ TTimestamp
These value types have specific sets of methods. i.e. TTimestamp value types are working
internally with the php native DateTime class.
TString has a bunch of methods to manipulate the output string.
All value type method are fluently designed.
v0.2:
- introducing ValueType Objects:
+ TString (published)
+ TNumber (published)
+ TBit (published)
+ TEnum (published)
+ TLob (published)
+ TTimestamp (published)
C# like data objects.
SAMPLE:
class Model_City extends TypeSafeStruct {
private $int_ID;
private $char_Name;
private $char_CountryCode;
private $char_District;
private $int_Population;
public function __set($key,$value) {
$type = $this->getPropertyType($key);
if($type and $this->hasProperty($key)) {
$this->{$type."_".$key} = $value;
} else {
$this->{"set".$key}($value);
}
}
public function __get($key) {
return $this->{$key};
}
}
$link = mysql_connect('localhost', 'root', 'pwd');
if (!$link) die('no connection established: ' . mysql_error());
$db = mysql_select_db('dbase', $link);
if (!$db)die ('no able to use db: ' . mysql_error());
$result = mysql_query("SELECT * FROM City LIMIT 4;");
if(!$result) die("no result set: ". mysql_error());
while($row=mysql_fetch_object($result, "Model_City")){
echo $row->getName()->toUpper()->padRight(15);
echo $row->getCountryCode()->toUpper()->padRight(5);
echo $row->getDistrict()->toUpper()->padRight(15);
echo $row->getPopulation()->format(0,",",".");
echo "\n";
}
mysql_close($link);
Click here for detailed information about this class on phpclasses.org