简体   繁体   中英

PHP OOP -> if statements in __construct vs calling functions direcly (performane and future)

I have a user class which has username, email and user level and it has methods such as ChangePassword, ChangeEmail, ChangeUserLevel, DeleteUser and Adduser.

Currently the class performs whatever it needs to do based on the data posted to the page which has $user = new User(name,email,secure_level) . So for example if you've submited the change password form to the page with instantiated user object in __construct it has several if statments -> such as:

If ($_POST['changePassword']) {
    $this -> changePassword(); }

and continues like that for other methods of the class. So my question is:

Is this a good way of handling these events or would it be better to do something like:

$user = new User(name,email,secure_level);
if ($_POST['changePassword']) {
   $user->changePassword(); }

By better I mean performance wise and possible future pitfalls.

(I have Login class, Registration class and Web Page class that are orginised in the similar manner)

Thank you in advance - I've just started learning PHP so I am not sure about anything I do.

Yes, the second option is better. User is a Model class (business logic abstraction) and as such shouldn't interact with web requests ( $_POST and friends) directly, this is a task for a Controller, not for models.

Imagine at some later point you'll have to write a command line script that manages users. If you keep User interface clean of web logic, you can reuse it in this script and just change the controller (replace $_POST[xxx] with $argv or similar).

There are a million ways to go about it. I personally use one function in my user class that goes:

updateUser($username = null, $password = null, $email = null)

And then any field that isn't null will be updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM