【问题标题】:PHP OOP saving, getting class properties to databasePHP OOP保存,将类属性获取到数据库
【发布时间】:2012-03-16 02:22:29
【问题描述】:

我正在尝试学习 oop。我正在使用 PHP-MySQL。而且我在使用 oop 方式(保存、更新、获取等)的数据库作业方面遇到了麻烦。

让我用一个示例项目来解释一下。

假设我想创建一个具有多种用户类型的网站。我有一个带有枚举“类型”字段的数据库表。我做了这样的课程:

abstract class User {
 //common properties, functions etc.. like id, username.
}

class Admin extends User {
 protected $type = "ADMIN";
 //I want here to have admin specific fields, functions etc...
}

...以及其他一些类似的用户类型。事情就是这样。我想要一个可以将对象保存和更新到数据库中的通用类。这样做的方法是什么?我将制作一个像 $user = new User(); 这样的对象bla .. bla .. 我会说“保存此用户”,但如何?我是否必须为每个具有特定 SQL 语句的类创建函数,例如“INSERT INTO table(name, pass, etc) VALUES ('name', 'pass', etc)”?

另一点是我想要一个返回对象的通用工厂类。举个例子,我会说“获取具有此 ID 的用户,如果该用户是管理员或其他类似的类,则使用管理员类对其进行实例化”。

我需要一些关于“如何用对象实例化 mysqli_fetch_assoc() 结果”的帮助。这将返回一个数组。我需要像 "$object->setId(returned_array["id"])" 那样做吗?

我看过一些书籍,如 PHP in Action、PHP 对象、模式和实践,但找不到这个数据库特定的主题。我希望我能很好地解释它,并为我的英语不好感到抱歉:)

【问题讨论】:

    标签: php oop design-patterns database-design


    【解决方案1】:

    这是一个示例 PDO CRUD 类和示例用法,希望它为您指明正确的方向:

    <?php
    /*** a new crud object ***/
    $crud = new crud();
    
    /*** The DSN ***/
    $crud->dsn = "mysql:dbname=yourDB;host=localhost";
    
    /*** MySQL username and password ***/
    $crud->username = 'username';
    $crud->password = 'password';
    
    
    /*** array of values to insert ***/
    $values = array(array('user'=>'bob', 'some_colum'=>'somevalue'));
    /*** insert the array of values ***/
    $crud->dbInsert('users', $values);
    
    /*** select all records from table ***/
    $records = $crud->rawSelect('SELECT * FROM users');
    
    /*** fetch only associative array of values ***/
    $rows = $records->fetchAll(PDO::FETCH_ASSOC);
    
    /*** example display the records ***/
    foreach($rows as $row){
        foreach($row as $fieldname=>$value){
            echo $fieldname.' = '.$value.'<br />';
        }
    }
    
    /*** update the user ***/
    $crud->dbUpdate('users', 'user', 'bobs_new', 'id', 3);
    
    /*** get the 3rd record ***/
    $res = $crud->dbSelect('users', 'id', 3 );
    
    /*** show the results ***/
    foreach($res as $row){
        echo $row['user'].' = '.$row['some_colum'].'<br />';
    }
    
    
    
    class crud{
    
        private $db;
        /**
         * Set variables
         */
        public function __set($name, $value)
        {
            switch($name)
            {
                case 'username':
                    $this->username = $value;
                    break;
    
                case 'password':
                    $this->password = $value;
                    break;
    
                case 'dsn':
                    $this->dsn = $value;
                    break;
    
                default:
                    throw new Exception("$name is invalid");
            }
        }
    
        /**
         * @check variables have default value
         */
        public function __isset($name){
            switch($name)
            {
                case 'username':
                    $this->username = null;
                    break;
    
                case 'password':
                    $this->password = null;
                    break;
            }
        }
    
        /**
         * @Connect to the database and set the error mode to Exception
         * @Throws PDOException on failure
         */
        public function conn(){
            isset($this->username);
            isset($this->password);
            if (!$this->db instanceof PDO)
            {
                $this->db = new PDO($this->dsn, $this->username, $this->password);
                $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }
        }
    
    
        /**
        * @select values from table
        * @access public
        * @param string $table The name of the table
        * @param string $fieldname
        * @param string $id
        * @return array on success or throw PDOException on failure
        */
        public function dbSelect($table, $fieldname=null, $id=null){
            $this->conn();
            $sql = "SELECT * FROM `$table` WHERE `$fieldname`=:id";
            $stmt = $this->db->prepare($sql);
            $stmt->bindParam(':id', $id);
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    
    
        /**
         * @execute a raw query
         * @access public
         * @param string $sql
         * @return array
         */
        public function rawSelect($sql){
            $this->conn();
            return $this->db->query($sql);
        }
    
        /**
         * @run a raw query
         * @param string The query to run
         */
        public function rawQuery($sql){
            $this->conn();
            $this->db->query($sql);
        }
    
    
        /**
         * @Insert a value into a table
         * @acces public
         * @param string $table
         * @param array $values
         * @return int The last Insert Id on success or throw PDOexeption on failure
         */
        public function dbInsert($table, $values){
            $this->conn();
            /*** snarg the field names from the first array member ***/
            $fieldnames = array_keys($values[0]);
            /*** now build the query ***/
            $size = sizeof($fieldnames);
            $i = 1;
            $sql = "INSERT INTO $table";
            /*** set the field names ***/
            $fields = '( ' . implode(' ,', $fieldnames) . ' )';
            /*** set the placeholders ***/
            $bound = '(:' . implode(', :', $fieldnames) . ' )';
            /*** put the query together ***/
            $sql .= $fields.' VALUES '.$bound;
    
            /*** prepare and execute ***/
            $stmt = $this->db->prepare($sql);
            foreach($values as $vals)
            {
                $stmt->execute($vals);
            }
        }
    
        /**
         * @Update a value in a table
         * @access public
         * @param string $table
         * @param string $fieldname, The field to be updated
         * @param string $value The new value
         * @param string $pk The primary key
         * @param string $id The id
         * @throws PDOException on failure
        */
        public function dbUpdate($table, $fieldname, $value, $pk, $id){
            $this->conn();
            $sql = "UPDATE `$table` SET `$fieldname`='{$value}' WHERE `$pk` = :id";
            $stmt = $this->db->prepare($sql);
            $stmt->bindParam(':id', $id, PDO::PARAM_STR);
            $stmt->execute();
        }
    
    
        /**
         * @Delete a record from a table
         * @access public
         * @param string $table
         * @param string $fieldname
         * @param string $id
         * @throws PDOexception on failure
         * */
        public function dbDelete($table, $fieldname, $id){
            $this->conn();
            $sql = "DELETE FROM `$table` WHERE `$fieldname` = :id";
            $stmt = $this->db->prepare($sql);
            $stmt->bindParam(':id', $id, PDO::PARAM_STR);
            $stmt->execute();
        }
    }
    
    ?>
    

    【讨论】:

      【解决方案2】:

      我认为您需要一个 ORM 框架。自己很难创建一个好的框架,但你可以找到一些现有的框架。请注意不要使用具有活动记录模式的框架,因为它是一种反模式。

      要获取对象:http://www.php.net/manual/en/mysqli-result.fetch-object.php

      但我也建议你以OO方式使用mysqli

      $resource = new mysqli(/* ... */);
      $resource->fetch_object(/* ... */)
      

      【讨论】:

      • 我差点忘了:试试 PDO ;-)
      • 看来我需要了解 ORM 的东西。这就是我需要的。感谢您的建议,我会尝试 PDO :)
      猜你喜欢
      • 1970-01-01
      • 2017-06-09
      • 2014-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多