I am writing a library that has components and component properties. The VAST majority of the time, properties can only be specified once on a component. But certain property types can be specified multiple times. Because of this, getProperty() has a bit of an annoying and inconvenient requirement in that it has to return an array, even though MOST of the time it is only returning one property. Let me give you an example:
I have an Event component. On the event component, I have the following properties:
Created - date/time it was created
DtStart - date/time the event starts
DtEnd - date/time the event ends
Description - Description of the event
Comment - Arbitrary comments about the event (this is the only property that can be set multiple times).
So, when I need one of the above properties, I call Event::getProperty($propname). Let's say I need the DtStart property. I call $event->getProperty('DtStart'). What is returned is array('2014-04-26 9:00pm'). When I call $event->getProperty('COMMENT') I get array('Some comment about the event', 'Some other comment').
In the above examples, the properties returned are actually Property objects. Not strings. What I really want is for getProperty() to return a property object, not an array of property objects. Especially since almost ALWAYS it is just going to be an array with one object in it. But at the same time, I need a consistent interface. I don't want to return an object sometimes and an array of objects other times. So what is the solution? How do I solve this problem?
Ideas on how to implement getProperty()
Moderator: General Moderators
Re: Ideas on how to implement getProperty()
Is it known by the calling code whether there (could be) multiple values? How about another method?
- getProperty() returns one value; in the case of multiple values it still just returns one
- getPropertyArray() returns an array of values; in the case of one value it still returns an array
- getProperty() returns one value; in the case of multiple values it still just returns one
- getPropertyArray() returns an array of values; in the case of one value it still returns an array
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
Re: Ideas on how to implement getProperty()
You could return an object that is iterable and has magic methods so it can be accessed as an single value/object or an array. That would make the code accessing the returned values all the same.
(#10850)