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.

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

报告相同问题?

悬赏问题

  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义