Doubt about data return in PHP POO

Asked

Viewed 140 times

0

I’m learning about object-oriented programming in PHP, classes, hierarchies and so on. Reading a few topics right here on stackoverflow I found the solution to my problem with the user control class, but I got a question regarding this.

The class would be:

class UserService
{
protected $_email;    // using protected so they can be accessed
protected $_password; // and overidden if necessary
protected $_user;     // stores the user data

public function __construct($email, $password) 
{
   $this->_email = $email;
   $this->_password = $password;
}
public function login()
{
    $user = $this->_checkCredentials();
    if ($user) {
        $this->_user = $user; // store it so it can be accessed later
        $_SESSION['user_id'] = $user['id'];
        return $user['id'];
    }
    return false;
}

protected function _checkCredentials()
{

    /* Faz a rotina para verificar se o usuário está no banco de dados*/
    /* e se a senha confere */

    /* Se OK retorna os dados do usuário, se não, retorna false */

}   
}

I am in doubt on how to use this class if I want to return only the username for example.

To log in the user I understood, would be:

session_start();
include("class.user.php");

$user = new UserService($_POST['email'], $_POST['pass']);

But if I want to return only the name (or some other data) of the user already logged in, without having to pass the parameters "email" and "password" again?

I would have to create a function within the class for me to pass the user ID stored in $_SESSION and the class would return the data, but I would have to instantiate the class using "new" again?

For example, in the class, add:

public function getUserName($uID)
{
   /* Verifica se o usuário está logado e busca o nome no DB */       
}

And in the main file (considering that the user has already been previously logged in):

session_start();
include("class.user.php");

$user = new UserService();

$userName = $user->getUserName($_SESSION['user_id']);

echo $userName;

That is correct?

EDIT: This class is just a draft of what I intend to do, I understand that it is necessary to correct some excerpts, sanitize the fields, encrypt the password and etc, this is just to demonstrate my doubt.

1 answer

0

All you have to do is set session_start() in the __construct, case after login you already put the $_SESSION['nome'] then I’d be like this:

  public function getUserName()
  {
    return $_SESSION['nome'];
  }
  • Right, but when calling the class I need to call the "new" or instantiate the class directly?

  • If the class is not Static you always have to instantiate with the new. if it is Static you only need to do so Userservice::getUserName(); do not forget that you have to include one in the class at the beginning of the file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.