2012-02-26 8 views
1

私はoopを学びたいです。私はPHP-MySQLに取り組んでいます。そして、私はoopの方法(保存、更新、取得など)でデータベースの仕事に困っています。PHP OOPを保存し、クラスプロパティをデータベースに追加しています

私は例プロジェクトでそれを説明しましょう。

複数のユーザータイプを持つサイトを作りたいとします。私は列挙型の "タイプ"フィールドを持つ単一のデータベーステーブルを持っています。そして、私はこれらのようなクラスを作った:

...そしてそのようないくつかのユーザータイプ。ここに事がある。オブジェクトをデータベースに保存して更新できる共通クラスが必要です。それを行う方法は何ですか?私は$ user = new User();のようなオブジェクトを作成します。 bla .. bla .. "私はこのユーザーを保存"と言うでしょうが、どうですか? "INSERT INTOテーブル(名前、パスなど)VALUES( '名前'、 'パス'など)のような特定のSQL文を持つ各クラスの関数を作成する必要がありますか?

別のポイントは、私にオブジェクトを返す共通のファクトリクラスが欲しいということです。たとえば、「この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

私はほとんど忘れてしまったんだ。それは私がORMの事について学ぶために必要になります –

+0

;-) PDOを試してみてください。それだけが必要。アドバイスありがとうと私はPDOを試してみる:) – emreyilmaz7c6

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

?> 
関連する問題