I'm trying to create an invoice class which is heavily dependent upon data from our DB. I've defined some class properties -- account number, invoice number, invoice date, and invoice details -- upon which most of the class methods will rely. The problem, or perhaps one of the problems, is that this data is scattered across numerous tables. Currently, the constructor requires only a single argument: invoice number. If this number does not correspond to a valid invoice number (ie. we have no such invoice) then most of the class methods will fail, including the methods required to assign values to the class properties. These, in turn, also need to point to valid database records.
I'm not really sure how to proceed from here. Does calling all the property setter methods (ie. $this->account_number = $this->getAccountNumber()) in the constructor and throwing exceptions if any of them returns FALSE make sense? Am I thinking about this completely wrong?
Validating objects?
Moderator: General Moderators
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
Re: Validating objects?
You can throw exceptions, or have some sort of convention for invalid return values (e.g. null), or you could implement a isValid() method that can be called before code section that use this object to verify that it was initialized properly. It really depends.
(#10850)
Re: Validating objects?
I had thought about having the various class methods return FALSE on failure and potentially having that bubble up as needed (ie. if method A calls method B and method B returns FALSE, then method A will also return FALSE). Seemed like an awful lot of repetition, though. I'm intrigued by your isValid() suggestion. How exactly did you mean? Instantiate the object using whatever number the constructor is provided, then have some class method check the database for a match which, in turn, would set a $_isValid property to either TRUE or FALSE?
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
Re: Validating objects?
Yeah ... it seem like by the end of the constructor running you should know whether the object is initialized properly.
(#10850)