I have programmed with procedural style a lot before and in these few months I have decided to go OOP.
Im a bit confused about OOP and PHP. Lets say I have Categories table and Pages table in my database. I would like to do a page-class and a category-class.
Lets say I would have a page that showed information about the category and there would be a list of pages that belong to the category. How would I implement that in OOP way?
I have thought that the category class would have a property (array) that would contain all the pages that it has. Well then comes the part that I`m confused about. Should I have a method that would get all the pages with correct categoryID from the database and should I instantiate all the rows as an Page-object?
Or should I have a setPages-method in the Category-class and getAllPages-method in the Pages-class and with that method I would set all the pages to the Category-class.
Huh Im lost. 😀
Create a Page class.
Create a Category class. One of its attributes should be an array of Page objects named $pages (or similar).
Create a method in the Category class called
getPages()which will return the $pages array. If you like, this can be a “lazy-loading” method that gets the pages from the DB when it is called and caches them in the $pages attribute. Or you can load all the Page objects when the Category object is created. Your call.Create a method in the Category class called
setPages($newArray)if you need or want to. This method should be used to overwrite the $pages array attribute with the value of the $newArray parameter.setX() methods are (traditionally) used to set the values of attributes, not to kick off DB lookups or other data generation schemes. They’ll look like this most of the time: