How to store user information in my User class?

  • (2 Pages)
  • +
  • 1
  • 2

23 Replies - 1630 Views - Last Post: 02 April 2018 - 02:37 PM Rate Topic: -----

#1 Foobarer   User is offline

  • D.I.C Regular

Reputation: 1
  • View blog
  • Posts: 261
  • Joined: 28-March 17

How to store user information in my User class?

Posted 31 March 2018 - 11:03 AM

As you probably know (I've been posting alot lately, after this one, no more flooding) I am working on my User class, and I want a private function that will store all the columns about the current user (username, first name, last name etc..) in an array, and then use this function to make some public "get" functions like so:
Class UserStuff{

    //more private properties
    private $user_credentials = array() //to store credentials 

    private function setUserCredentials() {
        $sql = "SELECT * FROM user WHERE user_id = :user_id";
        $this->stmt = $this->dbh->prepare($sql);
        $this->bind(':user_id', $this->user_id);
        try {
                $this->stmt->execute();
            } catch (PDOException $e) {
               array_push($this->error, $e->getMessage());
            $this->obj->error = $this->error;
            return $this->obj; 
        }
        
        $this->user_credentials = $this->stmt->fetch(//FETCH_OBJ? or FETCH_ASSOC?) //set credentials as array? object? which is the correct way?     

    }

    public function getFirstName(){
       return $this->user_credentials['firstname']; // like so (assuming 'firstname' is the database column for First name?)
    }

}

This post has been edited by Foobarer: 31 March 2018 - 11:18 AM


Is This A Good Question/Topic? 0
  • +

Replies To: How to store user information in my User class?

#2 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2560
  • View blog
  • Posts: 10,277
  • Joined: 03-December 12

Re: How to store user information in my User class?

Posted 31 March 2018 - 01:10 PM

There are easier ways, but I am out and canít give examples
Was This Post Helpful? 1
  • +
  • -

#3 Foobarer   User is offline

  • D.I.C Regular

Reputation: 1
  • View blog
  • Posts: 261
  • Joined: 28-March 17

Re: How to store user information in my User class?

Posted 31 March 2018 - 01:57 PM

But should I:
1) FETCH_OBJ or FETCH_ASSOC? (both return by column name)
2) After I fetch and store the fetched array in a private property - do you think I should create a getter function for each, i.e: getFirstName, getLastName,.., or just store them in a public property and access them directly:


$user = new User();
$username = $user->credentials['username']; //credentials is public array property

//or

$user = new User();
$username = $user->getUsername();

This post has been edited by Foobarer: 31 March 2018 - 01:57 PM

Was This Post Helpful? 0
  • +
  • -

#4 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2560
  • View blog
  • Posts: 10,277
  • Joined: 03-December 12

Re: How to store user information in my User class?

Posted 31 March 2018 - 02:29 PM

http://php-html.net/...troller-in-php/
Was This Post Helpful? 1
  • +
  • -

#5 Foobarer   User is offline

  • D.I.C Regular

Reputation: 1
  • View blog
  • Posts: 261
  • Joined: 28-March 17

Re: How to store user information in my User class?

Posted 31 March 2018 - 09:34 PM

I actually built my website closely to "MVC" :D !! Obviously messy, but in general I also separated it! this is interesting, I will read the tutorial, ty
But will it be related to my question of User class? Beacuse User class seem to be part of the "Controller" in the MVC pattern, or am I wrong? (Haven't read the entire article yet)

I would also like an example from you with relation to what I tried to do, I mean how would you separate the User class to match MVC? What's wrong with my class? because I can read stuff but without actual examples from experienced people I might keep reading and eventually think I understand but get a wrong concept if I get no feedback

This post has been edited by Foobarer: 31 March 2018 - 09:42 PM

Was This Post Helpful? 0
  • +
  • -

#6 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2560
  • View blog
  • Posts: 10,277
  • Joined: 03-December 12

Re: How to store user information in my User class?

Posted 31 March 2018 - 09:35 PM

User is a model. You use it to model the data presented from the database record.
Was This Post Helpful? 1
  • +
  • -

#7 Foobarer   User is offline

  • D.I.C Regular

Reputation: 1
  • View blog
  • Posts: 261
  • Joined: 28-March 17

Re: How to store user information in my User class?

Posted 31 March 2018 - 09:43 PM

Got it, and it already answered 1 of my questions (the question about public getters functions vs public property array):

From the tutorial:
include_once("model/Book.php");  
  
class Model {  
    public function getBookList()  
    {  
        // here goes some hardcoded values to simulate the database  
        return array(  
            "Jungle Book" => new Book("Jungle Book", "R. Kipling", "A classic book."),  
            "Moonwalker" => new Book("Moonwalker", "J. Walker", ""),  
            "PHP for Dummies" => new Book("PHP for Dummies", "Some Smart Guy", "")  
        );  
    }  
      
    public function getBook($title)  
    {  
        // we use the previous function to get all the books and then we return the requested one.  
        // in a real life scenario this will be done through a db select command  
        $allBooks = $this->getBookList();  
        return $allBooks[$title];  
    }  
      
      
}  


Then I should probably do something like:
include_once("model/User.php");  
  
class User 
{  
    public function getUserCredentials()
    {         
        return array(  
             //stuff
        );  
    }  
      
    public function getCredential($field)  
    {  
        $credentials= $this->getUserCredentials();  
        return $credentials[$field];  
    }        
      
}  

This post has been edited by Foobarer: 31 March 2018 - 09:54 PM

Was This Post Helpful? 0
  • +
  • -

#8 Ornstein   User is offline

  • New D.I.C Head

Reputation: 8
  • View blog
  • Posts: 17
  • Joined: 13-May 15

Re: How to store user information in my User class?

Posted 01 April 2018 - 01:43 AM

You'll notice that in the tutorial code you quoted, they include "model/Book.php" because they instantiate the Book class in the getBookList method i.e. the Book class is in model/Book.php. In your code, you're including "model/User.php" in the same file that your User class is in - which makes no sense. ;)/>

Also, your own getUserCredentials/getCredential implementations are a bit curious. In a case where the data you're working with is 1) so simple and 2) unlikely to change, there's no real reason for your own methods to call your own getters; you can just access the property directly.

As is often the case in programming, there's no objective "right way" to do any of this; you'll just decide what your priorities are (how easy the code is to work with, performance, etc) and which compromises to make in the process.

RE array vs objects: Again, this will be a decision you'll have to make based on your own understanding of your requirements, but as a general rule there's rarely any advantage to using an stdClass over an array. There may be cases where you want PDO to use a specific class instead of stdClass.

In any case, something like this is perhaps a beginner-friendly example of what you're looking for:

class User
{
    protected $fields = array();
    
    public function populate($userId)
    {
        // Query the DB to fetch $userId user and populate $this->fields.
        
        return $this;
    }
    
    public function get($field)
    {
        return isset($this->fields[$field]) ? $this->fields[$field] : null; 
    }
    
    public function all()
    {
        return $this->fields; 
    }
}

// This assignment works because the populate method returns "$this"

$user = (new \User)->populate(4);

echo $user->get('name');


Some people use PHP's "magic methods" to make the model/object easier to work with. This is an example of making a tradeoff - because
there's a (small) performance cost to using magic methods. Below is another example:

class User
{
    protected $fields = array();
    
    public function populate($userId)
    {
        // Query the DB to fetch $userId user and populate $this->fields.
        
        return $this;
    }
    
    public function __get($field)
    {
        return isset($this->fields[$field]) ? $this->fields[$field] : null; 
    }
    
    public function all($field)
    {
        return $this->fields; 
    }
}

$user = (new \User)->populate(4);

echo $user->name;


You may also prefer to use a separate class (think query builders, repository pattern, etc) to create and populate the user model/object e.g.

class User
{
    protected $fields;
    
    public function __construct($fields)
    {
        $this->fields = $fields;
    }
    
    public function __get($field)
    {
        return isset($this->fields[$field]) ? $this->fields[$field] : null; 
    }
    
    public function all($field)
    {
        return $this->fields; 
    }
}

class UserRepository
{
    protected $pdo;
    
    public function __construct($pdo)
    {
        $this->pdo = $pdo;
    }
    
    public function find($userId)
    {
        $userId = (int) $userId;
        
        $statement = $this->pdo->query("SELECT * FROM `users` WHERE `user_id` = {$userId}");
        
        $fields = $statement->fetch(\PDO::FETCH_ASSOC);
        
        return new \User($fields);
    }
}

// Only do this once

$pdo = new \PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'root', '');

$userRepository = new \UserRepository($pdo);

// Use the repository to get users

$user1 = $userRepository->find(2);
$user2 = $userRepository->find(4);

echo $user1->username;
echo '<br>';
echo $user2->username;


There's a lot more you could do to improve this (adding a way to specify which fields are fetched from the user table, adding support for more complex queries, adding a way to tell the repository which class to instantiate instead of User, etc), but you should have a good enough idea by now.

You may also benefit from looking at the ORM implementations of various frameworks.

PS. I notice you used the "private" keyword rather than "protected" in your earlier code. Unless you know the difference between the two and made an informed decision to use one over the other, "protected" is probably the one you should be using.

This post has been edited by andrewsw: 01 April 2018 - 02:01 AM
Reason for edit:: Removed previous quote, just press REPLY

Was This Post Helpful? 1
  • +
  • -

#9 andrewsw   User is online

  • Bouncy!
  • member icon

Reputation: 6563
  • View blog
  • Posts: 26,615
  • Joined: 12-December 12

Re: How to store user information in my User class?

Posted 01 April 2018 - 02:01 AM

Note that there is no need to quote the previous post in full, there is a Reply button further down the page.
Was This Post Helpful? 1
  • +
  • -

#10 Foobarer   User is offline

  • D.I.C Regular

Reputation: 1
  • View blog
  • Posts: 261
  • Joined: 28-March 17

Re: How to store user information in my User class?

Posted 01 April 2018 - 04:05 AM

View PostOrnstein, on 01 April 2018 - 01:43 AM, said:

In your code, you're including "model/User.php" in the same file that your User class is in - which makes no sense.


Haha didn't notice, my bad (Don't worry, it's not that I don't understand that, I just changed everything without payting attention)

Except for that, thanks for the comprehensive explanation! It helped
Was This Post Helpful? 0
  • +
  • -

#11 Foobarer   User is offline

  • D.I.C Regular

Reputation: 1
  • View blog
  • Posts: 261
  • Joined: 28-March 17

Re: How to store user information in my User class?

Posted 02 April 2018 - 09:14 AM

When using classes, should I fetch data using FETCH_OBJ or FETCH_ASSOC(To get the user data for example)? because I don't see any use for FETCH_OBJ currently, because FETCH_ASSOC also returns an associative array. I know it's class and we're talking about objects, but FETCH_ASSOC is also a good option

Perhaps you could explain which one do I need and why?

This post has been edited by Foobarer: 02 April 2018 - 09:14 AM

Was This Post Helpful? 0
  • +
  • -

#12 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2560
  • View blog
  • Posts: 10,277
  • Joined: 03-December 12

Re: How to store user information in my User class?

Posted 02 April 2018 - 09:18 AM

Have you read thru the documentation to see the differences?
Was This Post Helpful? 2
  • +
  • -

#13 Foobarer   User is offline

  • D.I.C Regular

Reputation: 1
  • View blog
  • Posts: 261
  • Joined: 28-March 17

Re: How to store user information in my User class?

Posted 02 April 2018 - 09:27 AM

Quote

PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set
PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set


I mean both of them return column name, I just wanted to know examples when one is preferred over the other (except for the fact that one is an object)

This post has been edited by Foobarer: 02 April 2018 - 09:30 AM

Was This Post Helpful? 0
  • +
  • -

#14 Foobarer   User is offline

  • D.I.C Regular

Reputation: 1
  • View blog
  • Posts: 261
  • Joined: 28-March 17

Re: How to store user information in my User class?

Posted 02 April 2018 - 09:55 AM

View PostOrnstein, on 01 April 2018 - 01:43 AM, said:



Let's say I've picked one of the options you suggested. I now want to work with the thing called dependency injection, and I want to do it with the Database class with the User class, does that mean I will need to do something like that:


Class Database
{

    public function __construct(){
        //create connection
        return $pdo;
    }

}

Class User
{

    private $pdo;

    public function __construct($pdo)
    {   $this->pdo = $pdo;
        
        //more stuff here
    }
}

//And create a User instance like so?
$pdo = new Database();
$user = new User($pdo); 



Is this a good way of implementing Dependency injection?

This post has been edited by Foobarer: 02 April 2018 - 09:57 AM

Was This Post Helpful? 0
  • +
  • -

#15 CTphpnwb   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3796
  • View blog
  • Posts: 13,742
  • Joined: 08-August 08

Re: How to store user information in my User class?

Posted 02 April 2018 - 10:02 AM

Look at the manual. You can cast the result directly to an object:
class User {

    public function showAttributes() {
        foreach($this as $key => $value) {
            print "$key => $value<br>";
        }

    }
}

$pdo = new PDO($dsn,$username,$password);

$sql = "SELECT * FROM users WHERE id = ? LIMIT 1";

$prepare = $pdo->prepare($sql);
$prepare->execute([1]);

$data = $prepare->fetchObject('User');

$data->showAttributes();


Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2