FeelsBadMan
FeelsBadMan

Reputation: 49

The usage of classes and OOP in PhP

I have got a little problems with OOP in php since this is my 1st time I am using it. I am trying to write my own authentication system without framework, just to undestand the basics of register/login/logout system. So I've made this so far, file connect.php:

<?php

class Dbconnect {
    private $servername;
    private $username;
    private $password;
    private $dbname;

    protected function connect() {
        $this->servername = "localhost";
        $this->username = "root";
        $this->password = "root";
        $this->dbname = "example";

        $conn = new mysqli($this->servername,$this->username,$this->password,$this->dbname);
        return $conn;
    }
}

Looks good, right? But now I don't understand how should my register.php file look like, I've wrote a procedural version, and don't know how to modify it to become OOP here it is:

<?php


include 'connect.php';

$Err = $emailErr = $usernameErr =  "";

//registration
if(isset($_POST['register'])) {
    $username = mysqli_real_escape_string($conn,$_POST['username']);
    $email = mysqli_real_escape_string($conn,$_POST['email']);
    $password = mysqli_real_escape_string($conn,$_POST['password']);

    if(empty($username) || empty($email) || empty($password)) {
        $Err = "Empty field(s)";
    } 

    if(!preg_match("/^[a-zA-z ]+$/", $username)){
        $usernameErr = "Use letters for user";
    } elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $emailErr = "Wrong email format";

            }

        }

           if ($Err == "" && $emailErr == "" && $usernameErr == "") {
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    $sql = "INSERT INTO users (username, email, password)
    VALUES('$username','$email','$hashed_password')";
    $result = $conn->query($sql);
    if($result) {
        header('location: http://' . $_SERVER['HTTP_HOST'] . '/test/success.php');
        exit();   

    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }


}

    }
?>

Can someone explain me how I should modify this file.Thanks.

Upvotes: 0

Views: 150

Answers (1)

tereško
tereško

Reputation: 58444

It my be different for other, but here is how I approach it: build it from top down.

So, you start by writing high level logic for the code task, that you want your code to implement:

$connection = new MySQLi('localhost', 'root', 'password', 'example');
$authenticator = new Authenticator($connection);

$activity = $_POST['action'] ?? 'default';
if ('register' === $activity) {
    $user = $authenticator->register($_POST['name'], $_POST['pass']);
}
if ('login' === $activity) {
    if ($authenticator->login($_POST['name'], $_POST['pass'])) {
        echo 'On';
    }
}

When the the top level methods are defined, you go a step deeper and will out the next layer (it can be one or multiple classes).

class Authenticator 
{
    private $connection;

    public function __construct($connection) {
         $this->connection = $connection;
    }

    public function register($username, $password) {
        $user = new User($username);
        $user->setPassword($password);
        $user->save($this->connection);
        return $user;
    }

    public function login($username, $password) {
        $user = new User($username);
        $user->load($this->connection);
        return $user->isMatchingPassword($password)
    }
}

At this point you can start see what other part of code you will have to fill out. In this case, from the code in this example, you would also need to implement a User class with at least the methods, that have already been mentioned.

At each step you tackle one specific scope of problems and that way, even when working on projects with huge complexity, you are not overwhelmed.

Few related notes

  • You cannot return from a constructor
  • There is no point in actually making a wrapper for DB connection. Instead you should use either MySQLi or PDO classes, that come with PHP.
  • Your code is vulnerable to SQL injections. Watch this video to see how you avoid such holes.
  • To find more learning materials, I would recommend watching lectures from this list.

Upvotes: 1

Related Questions