2012-02-26 32 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(); 
    } 
} 

?>