0

I am teaching myself PHP and am playing around with different projects to learn as much as possible. Right now I am working on a login script and everything works as expected. I originally wrote the script with just functions and no classes but then decided to incorporate classes to help myself learn them. I need some input on the following class. I don't feel switching to a class has accomplished anything because I simply inserted the function into the class. I know there is a better way to do this but am having trouble figuring it out.

Also, in each function I call the database connection class to establish a connection, is there a way to extend the database connection and use a variable for the connection so I don't have to call the class for each and every function?

I tried

<?php
include('dbClass.php');

class login_user extends Database {
  public $db = Database::getInstance();
  public $conn = $db->getConnection();

and I get the following error

Fatal error: Constant expression contains invalid operations in /Applications/MAMP/htdocs/login_project/includes/classes/login_userClass.php on line 5

dbClass.php

<?php
class Database {
    private $_connection;
    private static $_instance; //The single instance
    private $_host = SERVER;
    private $_username = USER;
    private $_password = PASS;
    private $_database = DB;
    /*
    Get an instance of the Database
    @return Instance
    */
public static function getInstance() {
    if(!self::$_instance) { // If no instance then make one
        self::$_instance = new self();
    }
    return self::$_instance;
}
// Constructor
private function __construct() {
    $this->_connection = new mysqli($this->_host, $this->_username,
        $this->_password, $this->_database);

    // Error handling
    if(mysqli_connect_error()) {
        trigger_error("Failed to conencto to MySQL: " . mysql_connect_error(),
             E_USER_ERROR);
    }
}
// Magic method clone is empty to prevent duplication of connection
private function __clone() { }
// Get mysqli connection
public function getConnection() {
    return $this->_connection;
}

}

login_userClass.php

<?php

class login_user {

  //see if the user exists
  function does_user_exist($username){
    $db = Database::getInstance();
    $conn = $db->getConnection();
    $stmt = $conn->prepare("SELECT user_name FROM users WHERE user_name = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->store_result();

    return $stmt->num_rows;
  }



//get the user hash and if create session variables and log users in.
  function get_user_hash($username, $password){
    $db = Database::getInstance();
    $conn = $db->getConnection();
    $stmt = $conn->prepare("SELECT id, user_name, user_password, user_email, user_registered FROM users WHERE user_name = ? LIMIT 1");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->bind_result($id, $user, $pass, $email, $user_registered);



while($stmt->fetch()){
        if(password_verify($password, $pass)){
            $_SESSION['user_id'] = $id;
            $_SESSION['user'] = $user;
            $_SESSION['email'] = $email;
            $_SESSION['registered_on'] = $user_registered;
            $_SESSION['loggedin'] = true;
            header("Location: http://".$_SERVER['HTTP_HOST']."/user.php");
            exit;
        } else {
            return false;
        }
    }
  }

}
Jonathon
  • 312
  • 2
  • 10
  • The first thing that comes to mind (I like to read code from bottom to top) is that a function named `get_user_hash` should return a hash (string), while yours either returns false, or terminates the script, modifies the session and redirects to another page. Those are big decisions to make for a function like that. – GolezTrol May 26 '16 at 13:46
  • @jonathon Which `login_user` class are you actually using, the first or the second? – Jeff Lambert May 26 '16 at 13:50
  • So should i have the hash returned in its own function, then use that result to verify the hash and log the user in, in another function? – Jonathon May 26 '16 at 13:50
  • Hello, friend. I congratulate you on your efforts to expand your tool box. I see you understand the concept of a Singleton, but I would also suggest using the concepts of object injection to establish a composition model for your login class. You need a constructor function (calm down, JavaScript people). You know the __construct. This will make it much easier to work with (including debugging), your login class down the road (http://php.net/manual/en/language.oop5.decon.php) – Anthony Rutledge May 26 '16 at 13:51
  • the second, the first one is something I tried that didn't work. The 2nd one if fully functional, i just know it can be better and would like some input. – Jonathon May 26 '16 at 13:51
  • Never use classes when you don't have to. – frosty May 26 '16 at 14:05
  • @frosty I didn't think I needed classes for this project, but I figured why not learn. – Jonathon May 26 '16 at 14:06
  • That's fine then. But you know why you shouldn't use them when you don't have to, right? – frosty May 26 '16 at 14:11
  • @frosty not exactly, I've read many different opinions on why you should and why you shouldn't. – Jonathon May 26 '16 at 14:16
  • People always try to over complicate things when they don't have to. Why write 10 pages of code, when you can achieve the same results with 5? It's the same thing with classes. Don't use them when you don't have to. – frosty May 26 '16 at 14:18
  • @frosty, gotcha. Right now it really doesn't make sense for me to write classes being that I am the only eyes seeing my code and the stuff I am writing really isn't that complex so I think functions would suffice. But, I would love to understand every aspect of PHP so I can increase my capabilities in writing PHP, ya know. – Jonathon May 26 '16 at 14:20

1 Answers1

0

you need to place initialization to some static method and call it after class definition

How to initialize static variables

Community
  • 1
  • 1
Richard
  • 1,045
  • 7
  • 11