Doubt on data return in PHP POO

0

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

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'm in doubt on how to use this class if I just want to return the user name for example.

To log in the user I understood it would be:

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

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

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

I would have to create a function inside the class so that I would pass the user ID stored in $ _SESSION and the class would return the data, but would I 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 (assuming the user has already been logged in previously):

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

$user = new UserService();

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

echo $userName;

Is this correct?

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

    
asked by anonymous 13.02.2016 / 08:02

1 answer

0

Just set session_start() to __construct , if after login you already put $_SESSION['nome'] there it would look like this:

  public function getUserName()
  {
    return $_SESSION['nome'];
  }
    
15.02.2016 / 21:15