---
layout: post
title: Clase PHP 5 para representar base de datos
date: 2006-05-04
## Make sure to change these
published: false
sitemap: true
hidden: true
sitemap: false
---

Ya hace algún tiempo que me tope con el artículo "Going dynamic with
PHP" de Jack Herrington, Senior Software Engineer, "Code Generation
Network" en el sitio developerWorks de IBM.

Nos muestra como aprovechando las nuevas características de programación
orientada a obejetos en PHP 5 se pueden crear objetos muy flexibles
capaces de crear metodos y variables miembro al vuelo.

En la actualidad utilizo el siguiente codigo en mis aplicaciones de PHP
como base, para una explicación de como funciona sugiero leer el
artículo en developerWorks, yo solo lo pongo aquí para disponer de el en
forma inmediata.


   getMessage()); }

   class DBObject
   {
   private $id = 0;
   private $table;
   private $fields = array();

   function __construct( $table, $fields )
   {
   $this->table = $table;
   foreach( $fields as $key )
   $this->fields[ $key ] = null;
   }

   function __get( $key )
   {
   return $this->fields[ $key ];
   }

   function __set( $key, $value )
   {
   if ( array_key_exists( $key, $this->fields ) )
   {
   $this->fields[ $key ] = $value;
   return true;
   }
   return false;
   }

   function load( $id )
   {
   global $db;
   $res = $db->query(
   "SELECT * FROM ".$this->table." WHERE ".
   $this->table."_id=?",
   array( $id )
   );
   $res->fetchInto( $row, DB_FETCHMODE_ASSOC );
   $this->id = $id;
   foreach( array_keys( $row ) as $key )
   $this->fields[ $key ] = $row[ $key ];
   }

   function insert()
   {
   global $db;

   $fields = $this->table."_id, ";
   $fields .= join( ", ", array_keys( $this->fields ) );

   $inspoints = array( "0" );
   foreach( array_keys( $this->fields ) as $field )
   $inspoints []= "?";
   $inspt = join( ", ", $inspoints );

   $sql = "INSERT INTO ".$this->table.
   " ( $fields ) VALUES ( $inspt )";

   $values = array();
   foreach( array_keys( $this->fields ) as $field )
   $values []= $this->fields[ $field ];

   $sth = $db->prepare( $sql );
   $db->execute( $sth, $values );

   $res = $db->query( "SELECT last_insert_id()" );
   $res->fetchInto( $row );
   $this->id = $row[0];
   return $row[0];
   }

   function update()
   {
   global $db;

   $sets = array();
   $values = array();
   foreach( array_keys( $this->fields ) as $field )
   {
   $sets []= $field.'=?';
   $values []= $this->fields[ $field ];
   }
   $set = join( ", ", $sets );
   $values []= $this->id;

   $sql = 'UPDATE '.$this->table.' SET '.$set.
   ' WHERE '.$this->table.'_id=?';

   $sth = $db->prepare( $sql );
   $db->execute( $sth, $values );
   }

   function delete()
   {
   global $db;
   $sth = $db->prepare(
   'DELETE FROM '.$this->table.' WHERE '.
   $this->table.'_id=?'
   );
   $db->execute( $sth,
   array( $this->id ) );
   }

   function delete_all()
   {
   global $db;
   $sth = $db->prepare( 'DELETE FROM '.$this->table );
   $db->execute( $sth );
   }
   }

   class Book extends DBObject
   {
   function __construct()
   {
   parent::__construct( 'book',
   array( 'author', 'title', 'publisher' ) );
   }
   }

   $book = new Book( );
   $book->delete_all();
   $book->{'title'} = "PHP Hacks";
   $book->{'author'} = "Jack Herrington";
   $book->{'publisher'} = "O'Reilly";
   $id = $book->insert();

   echo ( "New book id = $id\n" );

   $book->{'title'} = "Podcasting Hacks";
   $book->update();

   $book2 = new Book( );
   $book2->load( $id );
   echo( "Title = ".$book2->{'title'}."\n" );
   $book2->delete( );
   ?>