PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 12 ■ ENTERPRISE PATTERNS

abstract class Base {
static $DB;
static $stmts = array();


function __construct() {
$dsn = \woo\base\ApplicationRegistry::getDSN( );
if ( is_null( $dsn ) ) {
throw new \woo\base\AppException( "No DSN" );
}


self::$DB = new \PDO( $dsn );
self::$DB->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
}


function prepareStatement( $stmt_s ) {
if ( isset( self::$stmts[$stmt_s] ) ) {
return self::$stmts[$stmt_s];
}
$stmt_handle = self::$DB->prepare($stmt_s);
self::$stmts[$stmt_s]=$stmt_handle;
return $stmt_handle;
}


protected function doStatement( $stmt_s, $values_a ) {
$sth = $this->prepareStatement( $stmt_s );
$sth->closeCursor();
$db_result = $sth->execute( $values_a );
return $sth;
}
}
I use the ApplicationRegistry class to acquire a DSN string, which I pass to the PDO
constructor.


The prepareStatement() method simply calls the PDO class’s prepare() method, which returns a
statement handle. This is eventually passed to the execute() method. To run a query, though, in this
method, I cache the resource in a static array called $stmts. I use the SQL statement itself as the array
element’s index.
prepareStatement() can be called directly by child classes, but it is more likely to be invoked via
doStatement(). This accepts an SQL statement and a mixed array of values (strings and integers). This
array should contain the values that are to be passed to the database in executing the statement. The
method then uses the SQL statement in a call to prepareStatement(), acquiring a statement resource
that it uses with the PDOStatment::execute() method. If an error occurs, I throw an exception. As you will
see, all this work is hidden from the transaction scripts. All they need to do is formulate the SQL and get
on with business logic.
Here is the start of the VenueManager class, which sets up my SQL statements:


namespace woo\process;
//...


class VenueManager extends Base {
static $add_venue = "INSERT INTO venue
( name )

Free download pdf