I am facing some confusion because i have decided to convert from procedural to oop, I Find it more efficient.
So anyway I’ve got some questions i hope i find answers here 🙂
Let’s say am working on a php Registeration System which requires
1-Signup process
2-Activation Process
3-Login process (which requires)
Validating inputs
Validating Sessions, etc
The questions is: Should i make class for every process Or i can combine all of them into one class named ‘User’, with methods to login, signup, activate and so on, Or can i make 1 class named USER which has user’s properties, and signup, login classes extends it ?
-
Should i use separated classes for Sessions, Validating etc ? or just normal Checking inside the main class
-
Should i Separate ADMIN classes from normal classes ? meaning I have a USER class, which has methods, to login user, signup user etc, should i add more functions for admin like DELETE user, UPDATE user ? or separate it from the normal classes
You should make a
Userclass with different functions forloginsignupand whatever.You should separate different functions into as many classes/objects as you feel suits. For instance, with your
Userclass you might have aSessionclass which you use within yourUserclass to do the session management stuff. You could also create aPersonclass whichUserinherits from. This can have functions likeprintFullNameand such, whereas theUserclass has auth specific stuff likeloginandregister.Again, its up to you. You can do whatever you want. I would probably have a
UserAdminclass which has functions likedeleteUser($userid)andeditUser($userid)just because then its not confusing it with the auth side of things. However it can be done the other way. You could call aUserobject for a specific user and calldeleteUser()on that to delete the user. Its what you feel most comfortable with.As with all my answers, its what you want to do. There is no standard to this, and no rules. OOP is mainly about layering everything so that it makes sense, structurally, and about creating reusable code.
Another thing you want to look at is MVC programming. MVC stands for Model, View, Controller. In this set up you actually differentiate objects not by category (e.g. user, page etc) but by their function (e.g. model – connects to a database, view – has the code to layout a page, controller – computes stuff and passes data to the view). If you look at something like codeigniter then this will become more apparent to you.
Now you can create a model for users. In this model you can do all the database stuff, adding, editing, deleting users and such. This can then interface with a controller which will layout the page, e.g. seeing if the user is currently logged in, calling the user’s model and getting the name of the user from the model, then passing it to the view to display on screen. This will make much more sense when you start using frameworks like code igniter.
Anyway, good luck in your learning.