PHP OOP – Should Every Object Contain All the Data?

designobject-orientedPHP

I'm trying to learn PHP OOP "properly", and I was wondering, should the constructor grab all the information in the database and store it in the object?

To use an example I'm trying to create using PHP OOP, an internet comic website (much like XKCD's), would have two classes:

  • Catalogue (list and order of all the episodes)
  • Episode (data relating to that particular episode)

So, in this situation, should the Catalogue object get an array of all the episodeIDs (presumably this would be gotten in the constructor)? And if so, does that mean I have to update both the Object's array and the Database's array? And if so, what's the most common way of implementing this (presumably very common) action?

Best Answer

There are a few different approaches you can use to do this, depending on the data set, performance needs, and your general preference.

If there's an object that is used almost exclusively for display, you would probably want to query the dataset beforehand in some sort of Factory and then create the object by passing the data into the constructor.

If there's an object that touches a bunch of data sources and is used for different things, loading all of the data at instantiation might take a long time, and all of the object's data might not be needed every time that object is instantiated. You can leverage lazy loading to accomplish this goal.

If performance is a major concern, and the object stores a ton of data but is mostly immutable, you can use something like the Flyweight pattern, which allows you to actually treat a single object like a collection.

I highly recommend you try a few different ways of doing things. For a project such as yours, how you choose to instantiate and populate the object will probably matter little, but it will be a good and fun exercise in different object instantiation patterns.

As a final note, much of the knowledge you're gaining now about OOP can be applied to nearly any language you learn in the future.