Return to Snippet

Revision: 56288
at March 20, 2012 07:04 by osccar


Initial Code
abstract class DataObject
{
  protected $data = array();

  public function __construct( $data )
  {
    foreach ( $data as $key => $value ) {
        if ( array_key_exists( $key, $this->data ) )
          $this->data[$key] = $value;
    }
  }

  public function getValue( $field )
  {
    if ( array_key_exists( $field, $this->data ) )
      return $this->data[$field];
    else
      exit( "Field not found" );
  }

  public function getValueEncoded( $field )
  {
    return htmlspecialchars( $this->getValue( $field ) );
  }

  protected function connect()
  {
    try {
      $conn = new PDO( DB_DSN, DB_USERNAME, DB_PWD );
      $conn->setAttribute( PDO::ATTR_PERSISTENT, TRUE );
      $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    }
    catch ( PDOException $e) {
      exit( 'Connection failed: '. $e->getMessage() );
    }

    return $conn;
  }

  protected function disconnect( $conn )
  {
    $conn = NULL;
  }
}

Initial URL


Initial Description
Abstract class from which other classes can be derived to handle database access and data retrieval.
Constants for database connection (DB_DSN, DB_USERNAME, etc.) must be set in another php file (eg. config.php)

Initial Title
DataObject class

Initial Tags
class, data

Initial Language
PHP