简体   繁体   English

OOP PHP PDO我的第一个项目,我做对了吗?

[英]OOP PHP PDO My First Project , Am I doing right?

I am trying the learn OOP PHP and PDO,it is a bit confusing for now. 我正在尝试学习OOP PHP和PDO,目前有点混乱。 After reading lots of articles I decided to create my first project.And here is my code. 阅读大量文章后,我决定创建我的第一个项目,这是我的代码。

class db{

    private static $instance = NULL;
    private static $DSN = 'mysql:host=localhost;dbname=firstproject';

    private function __construct(){

    }

    public static function getInstance(){
        if(!self::$instance){
            self::$instance = new PDO(self::$DSN,'root','');
            self::$instance->exec('SET NAMES utf8');
        }   
        return self::$instance;
    }

    public function reg_insert($usr_name,$usr_password){
        self::$instance->query("INSERT INTO users VALUES(null,'$usr_name','$usr_password')");
    }


}

class insRegInfo{

    private $username;
    private $password;


    public function __construct($username,$password){

        $dbe = db::getInstance();
        db::reg_insert($username,$password);

    }



}

if(isset($_POST['register'])){

    $reg = new getRegInfo($_POST['username'],$_POST['password']);

}   

<head>
    <title>PDO Database Project</title>     
</head>

<body>

    <form action="" method="post">
        <p>
            <label>User Name</label>
            <input type="text" name="username"/>
        </p>

        <p>
            <label>Password</label>
            <input type="password" name="password"/>
        </p>

        <p>
            <input type="submit" name="register" value="Register" />
        </p>
    </form>

</body>

So as you see it is a simple registration system. 如您所见,这是一个简单的注册系统。 My question is,calling database class in another class like that, is it a true way or should I carry the insert function to database class, or maybe I need to define db class as parent and insRegInfo as child with extends method? 我的问题是,在这样的另一个类中调用数据库类,这是一种正确的方法,还是应该将insert函数携带到数据库类中,或者我需要使用Extended方法将db类定义为父类,将insRegInfo定义为子类?

Which way is better or is it just depends to me? 哪种方法更好还是仅取决于我?

I would start by using model/mapper. 我将从使用模型/映射器开始。 It's a very simple way to get plain objects and to be able to persist them to the database. 这是获取简单对象并将其持久化到数据库的一种非常简单的方法。 It also avoids mixing database calls and code (persistence logic) in with functionality (application or business logic). 它还避免将数据库调用和代码(持久性逻辑)与功能(应用程序或业务逻辑)混在一起。 Simple example: 简单的例子:

class User {
    public $id;
    public $username;

}

class UserMapper {
    /**
     * @param User $user
     */
    public function save(User $user) {

        if(isset($user->id)) {
            $statement = "Update users set username = ? where id = ?"
        } else {
            $statement = "insert into users set username = ?, id = ?"
        }
        $instance = db::getInstance();
        $sth = $instance->prepare($statement );
        $values_a = array($user->username, $user->id);
        $db_result = $sth->execute($values_a);
    }

    /**
     * @param int $userId
     * @return User
     */
    public function load($userId) {
        $statement = "select * from users where id = ?";
        $instance = db::getInstance();
        $sth = $instance->prepare($statement );
        $values_a = array($user->id);
        $db_result = $sth->execute($values_a);
        $returnUser = new User();
        $returnUser ->id       = $db_result[0]['id'];
        $returnUser ->username = $db_result[0]['username'];
        return $returnUser;
    }
}

I would also recommend using getters/setters, instead of direct member access, but this was just for simplicity of code... As you develop more models/mappers you will find common mapper functionality (saving, loading, deleting, finding) and you can refactor your code to contain the common logic so you don't have a bunch of copypasta. 我还建议您使用getters / setter代替直接成员访问,但这只是为了简化代码...随着开发更多的模型/映射器,您会发现常见的映射器功能(保存,加载,删除,查找),并且可以重构您的代码以包含通用逻辑,因此您没有一堆copypasta。

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

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