PHP Doctrine question

3 views
Skip to first unread message

Andrew

unread,
Nov 11, 2009, 2:37:00 PM11/11/09
to DallasPHP
Was very interested by talk last night given by Jake Smith. I
attended on the webcast. Didn't think of this question until
afterwards.

Does anyone know if there is a straightforward way using Doctrine to
update some required field for an insert, that might not be (possible
to be) explicitly specified, like a nextval coming from a sequence?

Again, great talk! Thanks again.

Andrew

jazzslider

unread,
Nov 13, 2009, 3:13:48 PM11/13/09
to DallasPHP
Couple of possible solutions. The easiest way is to define a preInsert
() method in your record object, and in that method have all the logic
necessary for defining your automatic value, e.g.:

[code]
class My_Record extends Doctrine_Record
{
public function preInsert(Doctrine_Event $event)
{
$this->nextval = $this->_findNextNextVal();
}

protected function _findNextNextVal()
{
$nextval = [something];
return $nextval;
}
}
[/code]

You can also do this at a somewhat higher level of abstraction by
defining an instance of Doctrine_Record_Listener and attaching it to
your record's table class; the actual preInsert() method would be
almost the same...

[code]
class My_Record_Listener extends Doctrine_Record_Listener
{
public function preInsert(Doctrine_Event $event)
{
$resource = $event->getInvoker();
$resource->nextVal = $this->_findNextNextVal();
}
}
[/code]

If you do it this way, you do need to manually attach the listener to
the Doctrine framework at the appropriate level…you can attach it to
the manager if you want it to apply to everything, the connection if
you want it to apply to everything on that connection, or the table if
you just want it to apply to a single table. In your case, the table
sounds appropriate, so...

[code]
$table = $doctrineConnection->getTable('Component');
$table->addRecordListener(new My_Record_Listener());
[/code]

For more on Doctrine event and record listeners (they're two different
kinds of classes; had a hard time realizing that, the documentation is
a bit sparse), check out http://www.doctrine-project.org/documentation/manual/1_1/en/event-listeners

Hope this helps (and is accurate)!
Adam
Reply all
Reply to author
Forward
0 new messages