2012-02-26 33 views
1

我在學習oop。我正在使用PHP-MySQL。而且我有使用oop方式數據庫作業的麻煩(保存,更新,獲取等)。PHP 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表(名稱,傳遞等)VALUES('name','pass'等)」)的類創建函數?

另一點是我想要一個常見的工廠類,返回一個對象。一個例子,我會說:「讓我的用戶有這個ID和實例化它與管理類,如果該用戶是一個管理員或其他類像那樣」。

我需要一些關於「如何像對象mysqli_fetch_assoc()結果一樣實例化」的幫助。這返回一個數組。我需要像「$ object-> setId(returned_array [」id「])」嗎?

我看過一些書籍,如PHP在行動,PHP對象,模式和實踐,但無法找到這個數據庫的具體主題。我希望我能解釋得很好,並對我的英語不好:)

回答

0

我認爲你需要一個ORM框架。很難單獨創建一個好的,但你可以找到一些現有的框架。請小心,不要使用具有活動記錄模式的框架,因爲它是反模式。

要提取的對象:http://www.php.net/manual/en/mysqli-result.fetch-object.php

但我也建議你在面向對象的方式使用mysqli

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

我差點忘了:試試PDO ;-) – 2012-02-26 07:32:31

+0

它看起來我需要了解ORM的東西。這就是我需要的。感謝您的建議,我會嘗試PDO :) – emreyilmaz7c6 2012-02-26 08:53:21

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(); 
    } 
} 

?>