Jump to content

Recommended Posts


<?php

class User {


public function Register() {

// do something


}

public function Login() {

// do something


}

public function Logout() {

// do something

}

public function CheckIfLoggedIn() {

// do something

}

public function ChangePassword() {

// do something

}

}

?>

 

Edited by B_CooperA
Link to comment
https://forums.phpfreaks.com/topic/285767-user-oop-class/#findComment-1466940
Share on other sites

I wrote you an example to give you an idea how to work with a php class.

class MyClass {
    
    protected $arg;
    
    // this function will be called if you create the class
    public function __construct($creationArg) {
        // using "$this" will refer to the class itself
        // the protected $arg defined at the start is avaible with $this
        $this->arg = $creationArg;
    }
    
    public function MyFunctionInClass() {
        // the $this is still avaible here.
        return $this->arg;
    }
}

$myClass = new MyClass('Hello world');
echo $myClass->MyFunctionInClass();
exit;
Link to comment
https://forums.phpfreaks.com/topic/285767-user-oop-class/#findComment-1466944
Share on other sites

Login, logout, and register are not methods on your User object for the simple reason that they are more then simple operations and include things your User should not be aware of.

 

So how do you think that i should go about it? Should i make a separate class for login, logout and register?

 

thanks for the 2 examples... i think that i know the basics (i red some posts in the tutorial section of this page, and i think that i got a good enough understanding on the basics for a OO beginner like myself), but i would need some good principles how to ground methods...

Edited by tastro
Link to comment
https://forums.phpfreaks.com/topic/285767-user-oop-class/#findComment-1466979
Share on other sites

Since login, logout, and register are application concerns, these should be handled in your controllers.

 

You could have a Password class that ensures a password is valid depending on your business rule (contains 1 uppercase letter, contains 1 number, is 8 characters long, ..).

 

class Password {
  private $value;
  
  public function __construct($value) {
    // validate password
    $this->value = $value;
  }
  
  public function createHash() {
    return BcryptPassword::fromPlainText($this->value);
  }
  
  public function equals($password) {
    //
  }
  
  public function __toString() {
    return $this->value;
  }
}

class BcryptPassword extends Password {
  // override createHash to return self
}
Then your User class can have:

 

class User {
  // first, last, email, ..
  private $bcryptPassword;
  
  // what makes a valid user?
  // you use this to 'register' a new user
  public function __construct($fname, $lname, Email $email, Password $password) {
    // 
  }
  
  public function setPassword(Password $password) {
    if (!empty($this->bcryptPassword)) {
      throw new PasswordAlreadySetException;
    }
    $this->bcryptPassword = (string) $password->createHash();
  }
  
  // no getPassword! See the below intention revealing methods.
  
  // you can use this function to implement a change password
  public function changePassword(Password $oldPassword, Password $newPassword) {
    if (!$this->passwordsMatch($oldPassword)) {
      throw new PasswordsDoNotMatchException;
    }
    
    $this->bcryptPassword = null;
    $this->setPassword($newPassword);
  }
  
  // you can use this function to verify that the user entered the correct credentials
  public function passwordsMatch(Password $password) {
    return $password->createHash()->equals($this->bcryptPassword);
  }
}
As you can see, because the domain is enforced at the entity level it is harder to make mistakes.

 

Since logout is mostly session, you don't have to provide any method for that in your User class.

Edited by ignace
Link to comment
https://forums.phpfreaks.com/topic/285767-user-oop-class/#findComment-1466983
Share on other sites

Thanks! But why shouldn't i include login, logout, register, check if logged in... In the User class? Only an user will need these methods right? So why should i put it into User? What am i not seeing? I just want to understand why these don't belong in the User class...

Link to comment
https://forums.phpfreaks.com/topic/285767-user-oop-class/#findComment-1467084
Share on other sites

I highly recommend reading Larry Ullman's :PHP Advanced and Object-Oriented Programming" ---The latest edition, for it help me out a lot.  Of course there are many different ways to do a user/members class.

 

Here's how I invoke a Member class:

<?php

# Member class - Store user info and functions to access/controll the flow of data.

class Member {

    // The member attributes containing required and optional information.
    // The attributes must correspond to the database table columns:

    private $id = NULL;
    private $userType = NULL; // Required (assigned enum)
    private $username = NULL; // Required 
    private $email = NULL; // Required   
    private $pass = NULL; // Required
    private $fullName = NULL;
    private $validation_code = NULL;
    private $address = NULL;
    private $city = NULL;
    private $state = NULL;
    private $zipCode = NULL;

    // Method returns the user ID:
    public function getId() {
        return $this->id;
    }

    // Grab the user's username:
    public function getUsername() {
        return $this->username;
    }

    // Grab the user's full name:
    public function getFullName() {
        return $this->fullName;
    }

    // Grab the password:
    public function getPass() {
        return $this->pass;
    }

    public function getUserType() {
        return $this->userType;
    }

    // Clear the password once user is logged in:
    public function clearPass() {
        $this->pass = NULL;
    }

    public function getEmail() {
        return $this->email;
    }

    // Method returns a Boolean if the user is an administrator:
    public function isAdmin() {
        return ($this->userType == 'admin');
    }

    public function isSysop() {
        return ($this->userType == 'sysop');
    }

    public function isNewUser() {
        return ($this->userType == 'public');
    }

    // Method returns a Boolean indicating if the user is an administrator
    // or if the user is the original author of the provided page:
    public function canEditPage(Page $page) {
        return (($this->isAdmin() && ($this->id == $page->getCreatorId())) || $this->isSysop());
    }

    // Method returns a Boolean indicating if the user is an administrator or an author:
    public function canCreatePage() {
        return ($this->isAdmin() || $this->isSysop());
    }

}

Then calling it is as simple as this (a part of my login in page):

    // Check against the database:
    $query = 'SELECT id, userType, username, email, pass, fullName, address, city, state, zipCode FROM users WHERE username=:username';
    $stmt = $pdo->prepare($query);
    $stmt->execute(array(':username' => $_POST['username']));

    $stmt->setFetchMode(PDO::FETCH_CLASS, 'Member');
    $stored_user_data = $stmt->fetch();

    // Verify Stored Hashed Password against input:
    if ($stored_user_data) {
        $result = password_verify($_POST['pass'], $stored_user_data->getPass());
    }
Edited by Strider64
Link to comment
https://forums.phpfreaks.com/topic/285767-user-oop-class/#findComment-1467087
Share on other sites

But why shouldn't i include login, logout, register, check if logged in... In the User class?

Since login, logout, and register are application concerns, these should be handled in your controllers.

What this means is that your User should not be aware of $_SESSION, $_COOKIE, $_POST, .. because if it does this means it is no longer re-usable in a different environment for example a REST API, CLI, ..

 

Also logging in has very little to do with the User itself, and more with the visitor representing that User, although an admin could represent ANY User.

 

At the very basic level we can consider something like this:

$_SESSION['loggedin'] = true;
And no User is involved. Same for logout:

unset($_SESSION['loggedin']);
Registration is nothing more then simply creating a new record in your database which is synonymous to new User(..).

 

In the example of a REST API (using an API key), login has a different meaning then in your app (using a login form). Which is why it is an application concern and not a domain concern.

Edited by ignace
Link to comment
https://forums.phpfreaks.com/topic/285767-user-oop-class/#findComment-1467092
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.