Object-oriented – OOP (php) for beginners – some unclarities

MySQLobject-orientedPHPsql

I started reading some tutorials about OOP, because I want to learn the basics.

I have a question about it. I understand how you can have a object "Car" and give it a color like this $oCar->setColor("white");

But there are some things unclear to me. Let's say I have a database with all kinds of cars. What is the best way to create the object "car"? A SQL-query instead the class?

And the other question is: how can I output a list of all cars? Do I need to create a object called "Garage" with has only one method within that selects all the cars from the database? Or does this kind of method belong in the "Car" object?

Best Answer

Let's say I have a database with all kinds of cars.

Yes, let's say you have that database in the memory of your computer (in-memory-database) and let's say that the interface to it are variables in PHP.

What is the best way to create the object "car"? A SQL-query instead the class?

Obviously an SQL query makes no sense here. First of all in PHP there is only one (and a half) way to create the object car and I'm sure you know that already:

new car;

Second SQL does not understand PHP directly. So using an SQL query would not make any sense.

Object orientation requires you to separate things. For example the object itself should not care about how (and when) it is stored into the memory, on disk, into an SQL database or printed out on paper to be typed in later again. If the car object would need to take care about all this, it would less be a car object but more the super-store-exchange-object called "car".

So just take care that one class is responsible for what it is good with:

And create new objects with new. You can find many hints how to make your code more simple and still improving it when writing OOP code in the post Don't be STUPID: GRASP SOLID! (Dec 2011; by NikiC).

Related Topic