简体   繁体   中英

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. 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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