Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Data Model Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Using standard php __construct (ors) with SS DataObject

Go to End

2 Posts   1889 Views


Community Member, 2 Posts

17 January 2011 at 5:58pm

Hey everyone,

I have been using Silverstripe full-time for over a year now and very happy with it, however I have been having a little trouble finding a solution to a surprisingly simple problem.

I want to use the standard php _construct on my DataObjects so that I can use some initialization logic in the constructor to set up the DataObject. This allows nicer and more intuitive syntax.

I want to be able to be able to do this:

foreach($orders as $order){
$completedOrder = new CompletedOrder($order);

I have been tying a constructor in CompletedOrder like this:

function __construct($order){
//etc etc

I cant seem to get the __construct to write to the db. It gets stuck in a recursive loop creating db rows.

Is there a simple elegant fix for this? It seems like it would be a really common use case. I know I could just call the method CompletedOrder::create($order) but syntactically that doesnt work as well. Now the loop looks like this:

$completedOrder = new CompletedOrder();
foreach($orders as $order){
$anotherCompletedOrder = completedOrder->create($order);

Does anyone know how to use __construct (ors) that write to the underlying db table of the DataObject? Any help would be much appreciated!!



Forum Moderator, 5521 Posts

18 January 2011 at 5:01pm

The default dataobject __construct defines a lot of functionality (take a look!) so you will need to at least call parent::__construct() as well. You should also keep the same arguments as the dataobject.php file to ensure you don't break anything.

I would potentially recommend not using __construct. Perhaps have a setOrder function.

$obj = new MyDataObject();

function setOrder($order) {