Extending Objects
Posted: Sat Mar 14, 2009 11:42 pm
I'm trying to figure out the best way to extend objects.
Reference the following code:
Now, to get a state object I can do this:
That gives me an instance of the State class. What I want to do is get the number of people that meet certain criteria in that state so I can generate a report. So my instinct was to extend the State class:
But something doesn't seem right here. In order for me to populate an instance of the CasesByState it looks like I have to do something like this:
So, that doesn't seem right. Maybe I need to extend the StatePeer class too?
Here is the code that populates an object from a PDO Statement in BaseStatePeer. StatePeer extends BaseStatePeer.
Just need to be pointed in the right direction.
Reference the following code:
Code: Select all
abstract class BaseState extends BaseObject implements Persistent {
// code
}
class State extends BaseState {
// code
}
Code: Select all
$c = new Criteria();
$c->add(StatePeer::NAME, 'Florida');
$state = StatePeer::doSelectOne();
Code: Select all
class CasesByState extends State {
public function getCaseCount($year = null) {
// get the number of cases in this state
}
}
Code: Select all
# create db criteria
$query = new Criteria();
$query->add(StatePeer::NAME, 'Florida');
# get an instance of State
$state = StatePeer::doSelectOne($c);
# create instance of CasesByState
$cases = new CasesByState();
# copy State into CasesByState
$state->copyInto($cases);
Here is the code that populates an object from a PDO Statement in BaseStatePeer. StatePeer extends BaseStatePeer.
Code: Select all
/**
* The returned array will contain objects of the default type or
* objects that inherit from the default.
*
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function populateObjects(PDOStatement $stmt)
{
$results = array();
// set the class once to avoid overhead in the loop
$cls = StatePeer::getOMClass();
$cls = substr('.'.$cls, strrpos('.'.$cls, '.') + 1);
// populate the object(s)
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$key = StatePeer::getPrimaryKeyHashFromRow($row, 0);
if (null !== ($obj = StatePeer::getInstanceFromPool($key))) {
$results[] = $obj;
} else {
$obj = new $cls();
$obj->hydrate($row);
$results[] = $obj;
StatePeer::addInstanceToPool($obj, $key);
} // if key exists
}
$stmt->closeCursor();
return $results;
}