donglin1192 2015-03-10 23:03
浏览 82
已采纳

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

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?

  • 写回答

1条回答 默认 最新

  • dongxu2398 2015-03-10 23:22
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?