Jump to:

3460 Posts in 1064 Topics by 739 members

Data Model Questions

SilverStripe Forums » Data Model Questions » Using standard php __construct (ors) with SS DataObject

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

Page: 1
Go to End
Author Topic: 1231 Views
  • nicola
    Avatar
    Community Member
    2 Posts

    Using standard php __construct (ors) with SS DataObject Link to this post

    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){
    parent::__construct();
    $this->$orderID;
    $this->$orderBlahblah;
    //etc etc
    $this->write();
    }

    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!!

    Cheers

  • Willr
    Avatar
    Forum Moderator
    5508 Posts

    Re: Using standard php __construct (ors) with SS DataObject Link to this post

    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();
    $obj->setOrder($order);
    $obj->write();

    ...
    function setOrder($order) {
    $this->$orderID;
    $this->$orderBlahblah;
    }

    1231 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.