I’m just starting out with a new project which has a product class. An object will represent a product.
Each product has any number of un-defined attributes (could be colour, could be foobar etc..). The product object will contain an array of either attribute objects:
class attr {
var type; // string, float, int etc..
var name; // the name
var value; // the value
...
(and then the product object has an array of these attr objects..)
OR should I store an array for each product:
class product {
var attributes = array('colour' => 'red', 'weight' => '11')
...
Obviously I can make the array 2d and store the attribute type if I needed to.
My main concern is that products may have 20 or so attributes and with lots of users to the site I’m creating this could use up loads of memory – is that right, or just a myth?
I’m just wondering if someone knows what the best practice is for this sort of thing.. the object method feels more right but feels a bit wasteful to me. Any suggestions/thoughts?
As a general advise I’m against early optimization, especially if that means turning your OO models into implicit (non-modeled concepts) things like arrays. While I don’t know what is the context in which you will be using them, having attributes as first class citizens will allow you to delegate behavior to them if you need, leading to a much cleaner design IMO. From my point of view you will mainly benefit in using the first approach if you need to manipulate the attributes, their types, etc.
Having said that, there are lots of frameworks that use the array approach for dynamically populating an object by using arrays and the
_get()/_set()magic methods. You may want to take a look for example at how Elgg handles the$attributesarray of theElggEntityclass to see it working and get some ideas.HTH