简体   繁体   English

PhP中类和OOP的用法

[英]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. 我在php中的OOP遇到了一些问题,因为这是我第一次使用它。 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: 所以到目前为止,我已经做到了,连接文件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: 但是现在我不明白我的register.php文件应该是什么样子,我已经编写了一个程序版本,并且不知道如何将其修改为OOP:

<?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. 有人可以解释一下我该如何修改此文件。谢谢。

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. 在这种情况下,还需要根据本示例中的代码,至少使用已经提到的方法来实现User类。

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 您不能从构造函数return
  • 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. 相反,您应该使用PHP附带的MySQLi或PDO类。
  • Your code is vulnerable to SQL injections. 您的代码容易受到SQL注入的攻击。 Watch this video to see how you avoid such holes. 观看此视频 ,了解如何避免此类漏洞。
  • To find more learning materials, I would recommend watching lectures from this list . 要查找更多学习资料,我建议您从此列表中观看讲座。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM