I'm relatively new using OOP in PHP. It's helped immensely in the organization and maintenance of my code, but I'd like to get better at designing my classes and using OOP as efficiently as I can. I've read the Gang of Four Design Patterns book, but still need some help. After building a few small apps, here's one thing I keep running across.
Let's say I'm building an application that keeps track of enrollment information for a school.
The way I would currently approach this is to have a class called student
, and methods within that class for CRUD on an individual student's record. It seems logical that I would have a constructor method for this class that took the student_id
as an argument, so I could reference it from within the object for all of those different CRUD operations.
But then, as I continue building the app, I run across situations where I need to run queries that return multiple students. For instance, something like, get_all_students_from_grade($grade)
, get_dropdown_of_all_students()
, etc. These methods don't apply to just one student, so it seems odd that I would have them as methods in my student
class, since I instantiated the object with one student_id
in mind. Obviously I can make it work this way, but it seems like I'm 'doing it wrong.' What is the best way to approach this?
The object-oriented design (OOD) question is centered around writing out a program to model a real-world system. For example, one OOD question I've been asked was to design a restaurant. The solution would involve specifying the important classes and methods for managing a restaurant.
For example, in a Library Automation Software, each library representative may be a separate object with its data and functions to operate on these data. The tasks defined for one purpose cannot refer or change data of other objects. Objects have their internal data which represent their state.
Separate the student
class (which is a domain class) from the operations on it (the business logic or data access, depending on the case) like:
student
- the domain object contains only datastudent_service
or student_dao
(Data Access Object) - performs operationsThis is sometimes considered as breaking the encapsulation, but it is an accepted best practice.
Here's more information on the matter. It provides more drawbacks from OOP point of view than the breaking of encapsulation. So even though it appears to be an accepted practice, it is not quite OOP.
Break it into two classes:
Your student class knows nothing about how it is stored relationally.
$students = student_repository.get_all_students_from_grade($grade)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With