Mysql
 sql >> Database >  >> RDS >> Mysql

Classe di connessione PDO/codice e design della classe

Questo è più o meno come lo faccio. Non sono sicuro che questo sia il modo migliore per farlo, ma per me funziona.

La mia classe factory è il CORE del mio codice. Da qui genero tutte le classi con cui lavoro. La mia classe factory viene salvata in un file separato factory.class.php .

Avendo una classe factory, ho solo bisogno di includere i file di classe solo una volta. Se non avessi questo, dovrei includere i miei file di classe per ogni file che deve usarlo. Se ho bisogno di aggiornare il nome di un file di classe in un secondo momento, devo solo effettuare l'aggiornamento nel file di classe di fabbrica.

Un altro motivo per creare un oggetto factory è stato quello di ridurre il numero di connessioni DB.

Salvo ogni classe come un file separato

Classe di fabbrica

include_once('person.class.php');
include_once('tracking.class.php');
include_once('costAnalyzis.class.php');
include_once('activity.class.php');

class Factory {
  function new_person_obj($id = NULL) { return new Person(Conn::get_conn(), $id); }  
  function new_tracking_obj($id = NULL) { return new Tracking(Conn::get_conn(), $id); }
  function new_costAnalyzis_obj() { return new CostAnalyzis(Conn::get_conn()); }
  function new_activity_obj() { return new Activity(Conn::get_conn()); }
}    

Classe di connessione

// I have this class in the same file as Factory class
// This creates DB connection and returns any error messages
class Conn {
  private static $conn = NULL;

  private function __construct() {}

  private static function init() {
      $conf = self::config();
      try { 
        self::$conn = new PDO($conf['dsn'], $conf['user'], $conf['pass'], array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
      } 
      catch (PDOException $e) {
        // We remove the username if we get [1045] Access denied
        if (preg_match("/\b1045\b/i", $e->getMessage())) 
          echo "SQLSTATE[28000] [1045] Access denied for user 'name removed' @ 'localhost' (using password: YES)";
        else
          echo $e->getMessage();  
      }
  }

  public static function get_conn() {
    if (!self::$conn) { self::init(); }
    return self::$conn;
  }

  // I used to get login info from config file. Now I use Wordpress constants
  private static function config() {
    $conf = array();

    $conf['user']    = DB_USER; //$config['db_user'];
    $conf['pass']    = DB_PASSWORD; //$config['db_password'];
    $conf['dsn']     = 'mysql:dbname='.DB_NAME.';host='.DB_HOST;

    return $conf;
  }  
}

Oggetti di classe diversi

Queste sono le tue classi. Qui è dove lavori con i tuoi dati Nel mio codice sto usando un'architettura a tre livelli, separando la presentazione, dal livello aziendale e dal livello degli oggetti dati.

class Person extends PersonDAO {

  function getPersonData($id) {
    $result = parent::getPersonData($id);

    // Here you can work with your data. If you do not need to handle data, just return result
    return $result;
  }
}


// I only have SQL queries in this class and I only return RAW results.
class PersonDAO {

  // This variable is also available from you mother class Person 
  private $db;

    // Constructor. It is automatically fired when calling the function.
    // It must have the same name as the class - unless you define 
    // the constructor in your mother class.
    // The &$db variable is the connection passed from the Factory class.
    function PersonDAO (&$db) {
      $this->db = &$db;
    }


  public function get_data($id) {
     $sql ="SELECT a, b, c
          FROM my_table
          WHERE id = :id";

     $stmt = $this->db->prepare($sql);
     $stmt->execute(array(':id'=> $id));
     $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

     return $result;
  }

  public function get_some_other_data() {
    $sql ="SELECT a, b, c
          FROM my_table_b";

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    return $result;      
  }
}

Fai lo stesso per le altre classi.

Mettere tutto insieme

Si noti che includiamo solo un file, i file di fabbrica. Tutti gli altri file di classe sono inclusi nel file di classe Factory.

// Include factory file
include_once('factory.class.php');

//Create your factory object
$person = Factory::new_person_obj();

//Get person data
$data = $person->getPersonData('12');

// output data
print_r($data);