I have a class named "Category" to handle all the operations and data about my categories. Now, my class is created however I need to find a way to build an object for each of the categories in my database.
In a PHP OOP structure, how should I do this? I was thinking about maybe making some kind of CategoryCollection class which only purpose would be to create an array containing a Category object for each of my categories, however I am not quite sure this would be the best way to achieve this.
2 Answers 2
You can always create multiple instances of a class! This is what classes are designed for! Each object will hold its own individual inner variables (unless they are static, in which case they are shared).
If you wish to store them all into a variable, you can use any collection type (List, Collection, Array). PHP offers its own array type
If you wish to pass a list of categories to a function, or return a list of categories. Fill the array with objects and pass it along.
It sounds like you need two classes:
- Category, which stores data about a single category. This is likely to be a simple POJO, typically holding data from a single database row. There may be some behavoural mehthods, but often there are none.
- CategoryList, which contains a list of categories, or possibly extends somethig like ArrayList. Typically this will supply only behavoural methods like
Category findCategoryByCode(String categoryCode)
andList<Category> findIncomeCategories()
.
It seems like your existing class is trying to fill both functions - try splitting out the responsibilities. Apologies that my answer is Java oriented. I have never used objects in PHP, but the same basics should apply.
-
2Why make a CategoryList instead of a List<Category>? This would add a class for no benefit.TZubiri– TZubiri2018年11月22日 07:58:28 +00:00Commented Nov 22, 2018 at 7:58
Explore related questions
See similar questions with these tags.
Category
(singular) which handles all the operations of all your categories (plural). It seems like a design failure. What exactly is theCategory
class as of now?