public function __construct()
Build an empty object.
this | //Implicit.// |
abstract protected function establishLiveConnection($mode)
Establish a live connection to a database service. This method should return a new connection. Lisk handles connection caching and management; do not perform caching deeper in the stack.
string | $mode | Mode, either 'r' (reading) or 'w' (reading and writing). |
AphrontDatabaseConnection | New database connection. |
protected function getConnectionNamespace()
Return a namespace for this object's connections in the connection cache. Generally, the database name is appropriate. Two connections are considered equivalent if they have the same connection namespace and mode.
string | Connection namespace for cache |
abstract protected function getDatabaseName()
wild |
protected function getEstablishedConnection($mode)
Get an existing, cached connection for this object.
mode | $mode | Connection mode. |
AphrontDatabaseConnection|null | Connection, if it exists in cache. |
protected function setEstablishedConnection($mode, $connection, $force_unique)
Store a connection in the connection cache.
mode | $mode | Connection mode. |
AphrontDatabaseConnection | $connection | Connection to cache. |
$force_unique |
this |
public function setForcedConnection($connection)
Force an object to use a specific connection.
This overrides all connection management and forces the object to use a specific connection when interacting with the database.
AphrontDatabaseConnection | $connection | Connection to force this object to use. |
wild |
protected function getConfiguration()
Change Lisk behaviors, like ID configuration and timestamps. If you want to change these behaviors, you should override this method in your child class and change the options you're interested in. For example:
protected function getConfiguration() { return array( Lisk_DataAccessObject::CONFIG_EXAMPLE => true, ) + parent::getConfiguration(); }
The available options are:
CONFIG_IDS Lisk objects need to have a unique identifying ID. The three mechanisms available for generating this ID are IDS_AUTOINCREMENT (default, assumes the ID column is an autoincrement primary key), IDS_MANUAL (you are taking full responsibility for ID management), or IDS_COUNTER (see below).
InnoDB does not persist the value of auto_increment across restarts, and instead initializes it to MAX(id) + 1 during startup. This means it may reissue the same autoincrement ID more than once, if the row is deleted and then the database is restarted. To avoid this, you can set an object to use a counter table with IDS_COUNTER. This will generally behave like IDS_AUTOINCREMENT, except that the counter value will persist across restarts and inserts will be slightly slower. If a database stores any DAOs which use this mechanism, you must create a table there with this schema:
CREATE TABLE lisk_counter ( counterName VARCHAR(64) COLLATE utf8_bin PRIMARY KEY, counterValue BIGINT UNSIGNED NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CONFIG_TIMESTAMPS Lisk can automatically handle keeping track of a `dateCreated' and `dateModified' column, which it will update when it creates or modifies an object. If you don't want to do this, you may disable this option. By default, this option is ON.
CONFIG_AUX_PHID This option can be enabled by being set to some truthy value. The meaning of this value is defined by your PHID generation mechanism. If this option is enabled, a `phid' property will be populated with a unique PHID when an object is created (or if it is saved and does not currently have one). You need to override generatePHID() and hook it into your PHID generation mechanism for this to work. By default, this option is OFF.
CONFIG_SERIALIZATION You can optionally provide a column serialization map that will be applied to values when they are written to the database. For example:
self::CONFIG_SERIALIZATION => array( 'complex' => self::SERIALIZATION_JSON, )
This will cause Lisk to JSON-serialize the 'complex' field before it is written, and unserialize it when it is read.
CONFIG_BINARY You can optionally provide a map of columns to a flag indicating that they store binary data. These columns will not raise an error when handling binary writes.
CONFIG_COLUMN_SCHEMA Provide a map of columns to schema column types.
CONFIG_KEY_SCHEMA Provide a map of key names to key specifications.
CONFIG_NO_TABLE Allows you to specify that this object does not actually have a table in the database.
CONFIG_NO_MUTATE Provide a map of columns which should not be included in UPDATE statements. If you have some columns which are always written to explicitly and should never be overwritten by a save(), you can specify them here. This is an advanced, specialized feature and there are usually better approaches for most locking/contention problems.
dictionary | Map of configuration options to values. |
public function getConfigOption($option_name)
Determine the setting of a configuration option for this class of objects.
const | $option_name | Option name, one of the CONFIG_* constants. |
mixed | Option value, if configured (null if unavailable). |
public function load($id)
Load an object by ID. You need to invoke this as an instance method, not a class method, because PHP doesn't have late static binding (until PHP 5.3.0). For example:
$dog = id(new Dog())->load($dog_id);
int | $id | Numeric ID identifying the object to load. |
obj|null | Identified object, or null if it does not exist. |
public function loadAll()
Loads all of the objects, unconditionally.
dict | Dictionary of all persisted objects of this type, keyed on object ID. |
public function loadAllWhere($pattern, ...)
Load all objects which match a WHERE clause. You provide everything after the 'WHERE'; Lisk handles everything up to it. For example:
$old_dogs = id(new Dog())->loadAllWhere('age > %d', 7);
The pattern and arguments are as per queryfx().
string | $pattern | queryfx()-style SQL WHERE clause. |
... | Zero or more conversions. |
dict | Dictionary of matching objects, keyed on ID. |
public function loadOneWhere($pattern, ...)
Load a single object identified by a 'WHERE' clause. You provide everything after the 'WHERE', and Lisk builds the first half of the query. See loadAllWhere(). This method is similar, but returns a single result instead of a list.
string | $pattern | queryfx()-style SQL WHERE clause. |
... | Zero or more conversions. |
obj|null | Matching object, or null if no object matches. |
protected function loadRawDataWhere($pattern)
$pattern |
wild |
public function reload()
Reload an object from the database, discarding any changes to persistent properties. This is primarily useful after entering a transaction but before applying changes to an object.
this |
public function loadFromArray($row)
Initialize this object's properties from a dictionary. Generally, you load single objects with loadOneWhere(), but sometimes it may be more convenient to pull data from elsewhere directly (e.g., a complicated join via queryData()) and then load from an array representation.
dict | $row | Dictionary of properties, which should be equivalent to selecting a row from the table or calling @{method:getProperties}. |
this |
public function loadAllFromArray($rows)
Initialize a list of objects from a list of dictionaries. Usually you load lists of objects with loadAllWhere(), but sometimes that isn't flexible enough. One case is if you need to do joins to select the right objects:
function loadAllWithOwner($owner) { $data = $this->queryData( 'SELECT d.* FROM owner o JOIN owner_has_dog od ON o.id = od.ownerID JOIN dog d ON od.dogID = d.id WHERE o.id = %d', $owner); return $this->loadAllFromArray($data); }
This is a lot messier than loadAllWhere(), but more flexible.
list | $rows | List of property dictionaries. |
dict | List of constructed objects, keyed on ID. |
public function setID($id)
Set unique ID identifying this object. You normally don't need to call this method unless with IDS_MANUAL.
mixed | $id | Unique ID. |
this |
public function getID()
Retrieve the unique ID identifying this object. This value will be null if the object hasn't been persisted and you didn't set it manually.
mixed | Unique ID. |
public function getPHID()
wild |
public function hasProperty($property)
Test if a property exists.
string | $property | Property name. |
bool | True if the property exists. |
protected function getAllLiskProperties()
Retrieve a list of all object properties. This list only includes properties that are declared as protected, and it is expected that all properties returned by this function should be persisted to the database. Properties that should not be persisted must be declared as private.
dict | Dictionary of normalized (lowercase) to canonical (original case) property names. |
protected function checkProperty($property)
Check if a property exists on this object.
$property |
string|null | Canonical property name, or null if the property does not exist. |
public function establishConnection($mode, $force_new)
Get or build the database connection for this object.
string | $mode | 'r' for read, 'w' for read/write. |
bool | $force_new | True to force a new connection. The connection will not be retrieved from or saved into the connection cache. |
AphrontDatabaseConnection | Lisk connection object. |
protected function getAllLiskPropertyValues()
Convert this object into a property dictionary. This dictionary can be restored into an object by using loadFromArray() (unless you're using legacy features with CONFIG_CONVERT_CAMELCASE, but in that case you should just go ahead and die in a fire).
dict | Dictionary of object properties. |
public function makeEphemeral()
Make an object read-only.
Making an object ephemeral indicates that you will be changing state in such a way that you would never ever want it to be written back to the storage.
wild |
private function isEphemeralCheck()
wild |
public function save()
Persist this object to the database. In most cases, this is the only method you need to call to do writes. If the object has not yet been inserted this will do an insert; if it has, it will do an update.
this |
public function replace()
Save this object, forcing the query to use REPLACE regardless of object state.
this |
public function insert()
Save this object, forcing the query to use INSERT regardless of object state.
this |
public function update()
Save this object, forcing the query to use UPDATE regardless of object state.
this |
public function delete()
Delete this object, permanently.
this |
protected function insertRecordIntoDatabase($mode)
Internal implementation of INSERT and REPLACE.
const | $mode | Either "INSERT" or "REPLACE", to force the desired mode. |
this |
protected function shouldInsertWhenSaved()
Method used to determine whether to insert or update when saving.
bool | true if the record should be inserted |
public function getTableName()
Retrieve the database table name. By default, this is the class name.
string | Table name for object storage. |
public function getIDKey()
Retrieve the primary key column, "id" by default. If you can not reasonably name your ID column "id", override this method.
string | Name of the ID column. |
protected function getIDKeyForUse()
wild |
public function generatePHID()
Generate a new PHID, used by CONFIG_AUX_PHID.
phid | Unique, newly allocated PHID. |
public function getPHIDType()
wild |
protected function willWriteData(&$data)
Hook to apply serialization or validation to data before it is written to the database. See also willReadData().
array | &$data |
wild |
protected function didWriteData()
Hook to perform actions after data has been written to the database.
wild |
protected function willSaveObject()
Hook to make internal object state changes prior to INSERT, REPLACE or UPDATE.
wild |
protected function willReadData(&$data)
Hook to apply serialization or validation to data as it is read from the database. See also willWriteData().
array | &$data |
wild |
protected function didReadData()
Hook to perform an action on data after it is read from the database.
wild |
protected function willDelete()
Hook to perform an action before the deletion of an object.
wild |
protected function didDelete()
Hook to perform an action after the deletion of an object.
wild |
protected function readField($field)
Reads the value from a field. Override this method for custom behavior of getField() instead of overriding getField directly.
string | $field | Canonical field name |
mixed | Value of the field |
protected function writeField($field, $value)
Writes a value to a field. Override this method for custom behavior of setField($value) instead of overriding setField directly.
string | $field | Canonical field name |
mixed | $value | Value to write |
wild |
public function openTransaction()
Increase transaction stack depth.
this |
public function saveTransaction()
Decrease transaction stack depth, saving work.
this |
public function killTransaction()
Decrease transaction stack depth, discarding work.
this |
public function beginReadLocking()
Begins read-locking selected rows with SELECT ... FOR UPDATE, so that other connections can not read them (this is an enormous oversimplification of FOR UPDATE semantics; consult the MySQL documentation for details). To end read locking, call endReadLocking(). For example:
$beach->openTransaction(); $beach->beginReadLocking(); $beach->reload(); $beach->setGrainsOfSand($beach->getGrainsOfSand() + 1); $beach->save(); $beach->endReadLocking(); $beach->saveTransaction();
this |
public function endReadLocking()
Ends read-locking that began at an earlier beginReadLocking() call.
this |
public function beginWriteLocking()
Begins write-locking selected rows with SELECT ... LOCK IN SHARE MODE, so that other connections can not update or delete them (this is an oversimplification of LOCK IN SHARE MODE semantics; consult the MySQL documentation for details). To end write locking, call endWriteLocking().
this |
public function endWriteLocking()
Ends write-locking that began at an earlier beginWriteLocking() call.
this |
public static function beginIsolateAllLiskEffectsToCurrentProcess()
wild |
public static function endIsolateAllLiskEffectsToCurrentProcess()
wild |
public static function shouldIsolateAllLiskEffectsToCurrentProcess()
wild |
private function establishIsolatedConnection($mode)
$mode |
wild |
public static function beginIsolateAllLiskEffectsToTransactions()
wild |
public static function endIsolateAllLiskEffectsToTransactions()
wild |
public static function shouldIsolateAllLiskEffectsToTransactions()
wild |
public static function closeInactiveConnections($idle_window)
Close any connections with no recent activity.
Long-running processes can use this method to clean up connections which have not been used recently.
int | $idle_window | Close connections with no activity for this many seconds. |
void |
public static function closeAllConnections()
wild |
public static function closeIdleConnections()
wild |
private static function closeConnection($key)
$key |
wild |
protected function applyLiskDataSerialization(&$data, $deserialize)
Applies configured serialization to a dictionary of values.
array | &$data | |
$deserialize |
wild |
public function __call($method, $args)
Black magic. Builds implied get*() and set*() for all properties.
string | $method | Method name. |
list | $args | Argument vector. |
mixed | get*() methods return the property value. set*() methods return $this. |
final protected function call($method, $args)
$method | ||
$args |
wild |
public function __set($name, $value)
Warns against writing to undeclared property.
$name | ||
$value |
wild |
public static function loadNextCounterValue($conn_w, $counter_name)
Increments a named counter and returns the next value.
AphrontDatabaseConnection | $conn_w | Database where the counter resides. |
string | $counter_name | Counter name to create or increment. |
int | Next counter value. |
public static function loadCurrentCounterValue($conn_r, $counter_name)
Returns the current value of a named counter.
AphrontDatabaseConnection | $conn_r | Database where the counter resides. |
string | $counter_name | Counter name to read. |
int|null | Current value, or `null` if the counter does not exist. |
public static function overwriteCounterValue($conn_w, $counter_name, $counter_value)
Overwrite a named counter, forcing it to a specific value.
If the counter does not exist, it is created.
AphrontDatabaseConnection | $conn_w | Database where the counter resides. |
string | $counter_name | Counter name to create or overwrite. |
$counter_value |
void |
private function getBinaryColumns()
wild |
public function getSchemaColumns()
wild |
public function getSchemaKeys()
wild |
public function getColumnMaximumByteLength($column)
$column |
wild |
public function getSchemaPersistence()
wild |
public function getAphrontRefDatabaseName()
wild |
public function getAphrontRefTableName()
wild |