New to PHP & OOP so bear with me… I’m in the optimistic early stages of designing and writing my first PHP & OOP website after a lifetime of writing crappy M$ VBA rubbish.
I have a class “User” which has a save method with the relevant database calls etc… (actually I have DB and DBUtils classes that handles the connection and CRUD – my business classes just call select, update, delete methods on DB Utils and pass associative arrays of data)
Anywho… My “User” class is extended by an “Admin” class which has some additional properties over and above “User” yada yada…
What is the best way to deal with the save method on “Admin”? I understand that if I add a save method to the Admin class it will supercede the one on User but I don’t want it to. I want to write the save method on Admin to only deal with the properties etc that are specific to the Admin objects and for the properties inherited from “User” to be dealt with in the User save method.
Does that make sense? Is it a specific OOP pattern I’m looking for? Any help or guidance with how I should design and structure this code would be appreciated.
EDIT: Whoa! Thanks for all the answers below. Not sure which is my preferred yet. I will have to do some playing around…
You are trying to implement the Active record pattern.
An approach in object persistence is to provide a common ancestor class [e.g.
BasicEntity] every subclass extends, which builds queries based on a given data schema:So your
Userclass will be like:And your
Adminclass:Calling
update()will build the right query based on class schema. This approach works with at a low complexity level, because you’ll notice that:additionalProperty];To resolve the first, you need composition of objects, so you don’t make your main table grow much [it just gets a reference to an external
AdditionalPropertyListentity, for example].To resolve the second, you have to keep the schema in external files or using inline annotations.
To resolve the third, you’ll have to write your own ORM [Object Relational Mapping], or much better switch to an existing one.
Anyway out of the learning benefits, I’d stand on the shoulder of giants and I’d pick a framework if you plan to build a scalable and maintainable application.