0

I have a very specific issue in mind, regarding on how to implement data models using instantiable classes. For example, let's say I have a list of cars in my database, and somewhere in my code I will have both the need to load a specific car, and to load all of the cars.

Does it make more sense to create a class Cars where $cars = new Cars; would return all cars, and when I need a specific car, I would call a static method Cars::getCar($id)?

Or vice-versa, have a class Car where $car = new Car($id) would return a specific car, and when I need all of them, I would call a static method Car::getAll()?

In both these cases, these static methods would in this case return simple arrays?

Would it make more sense (but it seems very impractical) to have both an instantiable class Car and an instantiable class Cars?

Is there yet another, ultimately better way?

Digital Ninja
  • 3,415
  • 5
  • 26
  • 51
  • First case makes the most sense for me – Sjoerd de Wit Oct 30 '14 at 09:48
  • 1
    Some people implement custom collection types like you would have `Cars` do, but I dislike this. I would suggest naming it `CarDealership` (or whatever is appropriate in your scenario) and have that hold a collection of `Car` objects as a member of the class. Now you can have `getCar($id)` and `getAllCars()` as a method on this class. – Jeroen Vannevel Oct 30 '14 at 09:48
  • On the background this should be only one class per one entity - `Car`. If you need all cars, then create a array (collection) of `Car` instances. A wrapper around it could provide you interfaces to that collection with `getAll()` method. – Royal Bg Oct 30 '14 at 09:50
  • You should have a `Car` class which represents *one* car, and a `CarStorage` or `CarRepository` or something along those lines which contains the code to get cars in and out of the database. That in aggregate is *the model*, "models" is not a real thing. None of this should be static methods. See the duplicate. – deceze Oct 30 '14 at 09:51
  • @RoyalBg When you say collection of Car instances, can you be more specific as to how I would achieve this in code? To have their instances, I would have to invoke the constructor on each returned row? – Digital Ninja Oct 30 '14 at 10:27

0 Answers0