* OpenExpedio ("xPDO") is an ultra-light, PHP 5.2+ compatible ORB (Object-
* Relational Bridge) library based around PDO (http://php.net/pdo/).
* Copyright 2010-2014 by MODX, LLC.
* This file is part of xPDO.
* xPDO is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* xPDO is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with
* xPDO; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA
* This is the main file to include in your scripts to use xPDO.
* @author Jason Coward <xpdo@opengeek.com>
* @copyright Copyright (C) 2006-2014, Jason Coward
* @license http://opensource.org/licenses/gpl-2.0.php GNU Public License v2
if (!defined('XPDO_PHP_VERSION')) {
* Defines the PHP version string xPDO is running under.
define('XPDO_PHP_VERSION', phpversion());
if (!defined('XPDO_CLI_MODE')) {
if (php_sapi_name() == 'cli') {
* This constant defines if xPDO is operating from the CLI.
define('XPDO_CLI_MODE', true);
define('XPDO_CLI_MODE', false);
if (!defined('XPDO_CORE_PATH')) {
* @internal This global variable is only used to set the {@link
* XPDO_CORE_PATH} value upon initial include of this file. Not meant for
$xpdo_core_path= strtr(realpath(dirname(__FILE__)), '\\', '/') . '/';
* @var string The full path to the xPDO root directory.
* Use of this constant is recommended for use when building any path in
define('XPDO_CORE_PATH', $xpdo_core_path);
if (!class_exists('PDO')) {
//@todo Handle PDO configuration errors here.
* A wrapper for PDO that powers an object-relational data model.
* xPDO provides centralized data access via a simple object-oriented API, to
* a defined data structure. It provides the de facto methods for connecting
* to a data source, getting persistence metadata for any class extended from
* the {@link xPDOObject} class (core or custom), loading data source managers
* when needed to manage table structures, and retrieving instances (or rows) of
* any object in the model.
* Through various extensions, you can also reverse and forward engineer classes
* and metadata maps for xPDO, have classes, models, and properties maintain
* their own containers (databases, tables, columns, etc.) or changes to them,
const OPT_AUTO_CREATE_TABLES = 'auto_create_tables';
const OPT_BASE_CLASSES = 'base_classes';
const OPT_BASE_PACKAGES = 'base_packages';
const OPT_CACHE_COMPRESS = 'cache_compress';
const OPT_CACHE_DB = 'cache_db';
const OPT_CACHE_DB_COLLECTIONS = 'cache_db_collections';
const OPT_CACHE_DB_OBJECTS_BY_PK = 'cache_db_objects_by_pk';
const OPT_CACHE_DB_EXPIRES = 'cache_db_expires';
const OPT_CACHE_DB_HANDLER = 'cache_db_handler';
const OPT_CACHE_DB_SIG_CLASS = 'cache_db_sig_class';
const OPT_CACHE_DB_SIG_GRAPH = 'cache_db_sig_graph';
const OPT_CACHE_EXPIRES = 'cache_expires';
const OPT_CACHE_FORMAT = 'cache_format';
const OPT_CACHE_HANDLER = 'cache_handler';
const OPT_CACHE_KEY = 'cache_key';
const OPT_CACHE_PATH = 'cache_path';
const OPT_CACHE_PREFIX = 'cache_prefix';
const OPT_CACHE_ATTEMPTS = 'cache_attempts';
const OPT_CACHE_ATTEMPT_DELAY = 'cache_attempt_delay';
const OPT_CALLBACK_ON_REMOVE = 'callback_on_remove';
const OPT_CALLBACK_ON_SAVE = 'callback_on_save';
const OPT_CONNECTIONS = 'connections';
const OPT_CONN_INIT = 'connection_init';
const OPT_CONN_MUTABLE = 'connection_mutable';
const OPT_HYDRATE_FIELDS = 'hydrate_fields';
const OPT_HYDRATE_ADHOC_FIELDS = 'hydrate_adhoc_fields';
const OPT_HYDRATE_RELATED_OBJECTS = 'hydrate_related_objects';
const OPT_LOCKFILE_EXTENSION = 'lockfile_extension';
const OPT_USE_FLOCK = 'use_flock';
const OPT_LOADER_CLASSES = 'loader_classes';
const OPT_ON_SET_STRIPSLASHES = 'on_set_stripslashes';
const OPT_SETUP = 'setup';
const OPT_TABLE_PREFIX = 'table_prefix';
const OPT_VALIDATE_ON_SAVE = 'validate_on_save';
const OPT_VALIDATOR_CLASS = 'validator_class';
const LOG_LEVEL_FATAL = 0;
const LOG_LEVEL_ERROR = 1;
const LOG_LEVEL_WARN = 2;
const LOG_LEVEL_INFO = 3;
const LOG_LEVEL_DEBUG = 4;
const SCHEMA_VERSION = '1.1';
* @var PDO A reference to the PDO instance used by the current xPDOConnection.
* @var array Configuration options for the xPDO instance.
* @var xPDODriver An xPDODriver instance for the xPDOConnection instances to use.
* A map of data source meta data for all loaded classes.
* A default package for specifying classes by name.
* An array storing packages and package-specific information.
public $packages= array ();
* {@link xPDOManager} instance, loaded only if needed to manage datasource
* containers, data structures, etc.
* @var xPDOCacheManager The cache service provider registered for this xPDO
public $cacheManager= null;
* @var string A root path for file-based caching services to use.
private $cachePath= null;
* @var array An array of supplemental service classes for this xPDO instance.
public $services= array ();
* @var float Start time of the request, initialized when the constructor is
* @var int The number of direct DB queries executed during a request.
public $executedQueries= 0;
* @var int The amount of request handling time spent with DB queries.
public $classMap = array();
* @var xPDOConnection The current xPDOConnection for this xPDO instance.
public $connection = null;
* @var array PDO connections managed by this xPDO instance.
private $_connections = array();
* @var integer The logging level for the xPDO instance.
protected $logLevel= xPDO::LOG_LEVEL_FATAL;
* @var string The default logging target for the xPDO instance.
protected $logTarget= 'ECHO';
* Indicates the debug state of this instance.
* @var boolean Default is false.
protected $_debug= false;
* A global cache flag that can be used to enable/disable all xPDO caching.
* @var boolean All caching is disabled by default.
public $_cacheEnabled= false;
* Indicates the opening escape character used for a particular database engine.
public $_escapeCharOpen= '';
* Indicates the closing escape character used for a particular database engine.
public $_escapeCharClose= '';
* Represents the character used for quoting strings for a particular driver.
* @var array A static collection of xPDO instances.
protected static $instances = array();
* Create, retrieve, or update specific xPDO instances.
* @param string|int|null $id An optional identifier for the instance. If not set
* a uniqid will be generated and used as the key for the instance.
* @param array|null $config An optional array of config data for the instance.
* @param bool $forceNew If true a new instance will be created even if an instance
* with the provided $id already exists in xPDO::$instances.
* @throws xPDOException If a valid instance is not retrieved.
* @return xPDO An instance of xPDO.
public static function getInstance($id = null, $config = null, $forceNew = false) {
$instances =& self::$instances;
if (!is_null($config) || $forceNew || empty($instances)) {
if ($forceNew || !array_key_exists($id, $instances) || !($instances[$id] instanceof xPDO)) {
$instances[$id] = new xPDO(null, null, null, $config);
} elseif ($instances[$id] instanceof xPDO && is_array($config)) {
$instances[$id]->config = array_merge($instances[$id]->config, $config);
if (!($instances[$id] instanceof xPDO)) {
throw new xPDOException("Error getting " . __CLASS__ . " instance, id = {$id}");
* This method is used to create a new xPDO object with a connection to a
* specific database container.
* @param mixed $dsn A valid DSN connection string.
* @param string $username The database username with proper permissions.
* @param string $password The password for the database user.
* @param array|string $options An array of xPDO options. For compatibility with previous
* releases, this can also be a single string representing a prefix to be applied to all
* database container (i. e. table) names, to isolate multiple installations or conflicting
* table names that might need to coexist in a single database container. It is preferrable to
* include the table_prefix option in the array for future compatibility.
* @param array|null $driverOptions Driver-specific PDO options.
* @throws xPDOException If an error occurs creating the instance.
* @return xPDO A unique xPDO instance.
public function __construct($dsn, $username= '', $password= '', $options= array(), $driverOptions= null) {
$this->config = $this->initConfig($options);
$this->setLogLevel($this->getOption('log_level', null, xPDO::LOG_LEVEL_FATAL, true));
$this->setLogTarget($this->getOption('log_target', null, XPDO_CLI_MODE ? 'ECHO' : 'HTML', true));
$this->addConnection($dsn, $username, $password, $this->config, $driverOptions);
if (isset($this->config[xPDO::OPT_CONNECTIONS])) {
$connections = $this->config[xPDO::OPT_CONNECTIONS];
if (is_string($connections)) {
$connections = $this->fromJSON($connections);
if (is_array($connections)) {
foreach ($connections as $connection) {
$connection['driverOptions']
$initOptions = $this->getOption(xPDO::OPT_CONN_INIT, null, array());
$this->config = array_merge($this->config, $this->getConnection($initOptions)->config);
$this->setPackage('om', XPDO_CORE_PATH, $this->config[xPDO::OPT_TABLE_PREFIX]);
if (isset($this->config[xPDO::OPT_BASE_PACKAGES]) && !empty($this->config[xPDO::OPT_BASE_PACKAGES])) {
$basePackages= explode(',', $this->config[xPDO::OPT_BASE_PACKAGES]);
foreach ($basePackages as $basePackage) {
$exploded= explode(':', $basePackage, 2);
if (strpos($path, ';')) {
$details= explode(';', $path);
if ($details && count($details) == 2) {
$this->addPackage($exploded[0], $path, $prefix);
$this->loadClass('xPDOObject');
$this->loadClass('xPDOSimpleObject');
if (isset($this->config[xPDO::OPT_BASE_CLASSES])) {
foreach (array_keys($this->config[xPDO::OPT_BASE_CLASSES]) as $baseClass) {
$this->loadClass($baseClass);
if (isset($this->config[xPDO::OPT_CACHE_PATH])) {
$this->cachePath = $this->config[xPDO::OPT_CACHE_PATH];
throw new xPDOException("Could not instantiate xPDO: " . $e->getMessage());
* Initialize an xPDO config array.
* @param string|array $data The config input source. Currently accepts a PHP array,
* or a PHP string representing xPDO::OPT_TABLE_PREFIX (deprecated).
* @return array An array of xPDO config data.
protected function initConfig($data) {
$data= array(xPDO::OPT_TABLE_PREFIX => $data);
} elseif (!is_array($data)) {
$data= array(xPDO::OPT_TABLE_PREFIX => '');
* Add an xPDOConnection instance to the xPDO connection pool.
* @param string $dsn A PDO DSN representing the connection details.
* @param string $username The username credentials for the connection.
* @param string $password The password credentials for the connection.
* @param array $options An array of options for the connection.
* @param null $driverOptions An array of PDO driver options for the connection.
* @return boolean True if a valid connection was added.
public function addConnection($dsn, $username= '', $password= '', array $options= array(), $driverOptions= null) {
$connection= new xPDOConnection($this, $dsn, $username, $password, $options, $driverOptions);
if ($connection instanceof xPDOConnection) {
$this->_connections[]= $connection;
* Get an xPDOConnection from the xPDO connection pool.
* @param array $options An array of options for getting the connection.
* @return xPDOConnection|null An xPDOConnection instance or null if no connection could be retrieved.
public function &getConnection(array $options = array()) {
$conn =& $this->connection;
$mutable = $this->getOption(xPDO::OPT_CONN_MUTABLE, $options, null);
if (!($conn instanceof xPDOConnection) || ($mutable !== null && (($mutable == true && !$conn->isMutable()) || ($mutable == false && $conn->isMutable())))) {
if (!empty($this->_connections)) {
shuffle($this->_connections);
$conn = reset($this->_connections);
if ($mutable !== null && (($mutable == true && !$conn->isMutable()) || ($mutable == false && $conn->isMutable()))) {
$conn = next($this->_connections);
$this->connection =& $conn;
$this->log(xPDO::LOG_LEVEL_ERROR, "Could not get a valid xPDOConnection", '', __METHOD__, __FILE__, __LINE__);
return $this->connection;
* Get or create a PDO connection to a database specified in the configuration.
* @param array $driverOptions An optional array of driver options to use
* when creating the connection.
* @param array $options An array of xPDO options for the connection.
* @return boolean Returns true if the PDO connection was created successfully.
public function connect($driverOptions= array (), array $options= array()) {
$this->getConnection($options);
if ($this->connection instanceof xPDOConnection) {
$connected = $this->connection->connect($driverOptions);
$this->pdo =& $this->connection->pdo;
* Sets a specific model package to use when looking up classes.
* This package is of the form package.subpackage.subsubpackage and will be
* added to the beginning of every xPDOObject class that is referenced in
* xPDO methods such as {@link xPDO::loadClass()}, {@link xPDO::getObject()},
* {@link xPDO::getCollection()}, {@link xPDOObject::getOne()}, {@link
* xPDOObject::addOne()}, etc.
* @param string $pkg A package name to use when looking up classes in xPDO.
* @param string $path The root path for looking up classes in this package.
* @param string|null $prefix Provide a string to define a package-specific table_prefix.
public function setPackage($pkg= '', $path= '', $prefix= null) {
if (empty($path) && isset($this->packages[$pkg])) {
$path= $this->packages[$pkg]['path'];
$prefix= !is_string($prefix) && array_key_exists('prefix', $this->packages[$pkg]) ? $this->packages[$pkg]['prefix'] : $prefix;
$set= $this->addPackage($pkg, $path, $prefix);
$this->package= $set == true ? $pkg : $this->package;
if ($set && is_string($prefix)) $this->config[xPDO::OPT_TABLE_PREFIX]= $prefix;
* Adds a model package and base class path for including classes and/or maps from.
* @param string $pkg A package name to use when looking up classes/maps in xPDO.
* @param string $path The root path for looking up classes in this package.
* @param string|null $prefix Provide a string to define a package-specific table_prefix.
public function addPackage($pkg= '', $path= '', $prefix= null) {
if (is_string($pkg) && !empty($pkg)) {
if (!is_string($path) || empty($path)) {
$this->log(xPDO::LOG_LEVEL_ERROR, "Invalid path specified for package: {$pkg}; using default xpdo model path: " . XPDO_CORE_PATH . 'om/');
$path= XPDO_CORE_PATH . 'om/';