Download the PHP package symlex/doctrine-active-record without Composer
On this page you can find all versions of the php package symlex/doctrine-active-record. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package doctrine-active-record
Object-oriented CRUD for Doctrine DBAL
As a lightweight alternative to Doctrine ORM, this battle-tested library provides Business Model and Database Access Object (DAO) classes that encapsulate Doctrine DBAL to provide high-performance, object-oriented CRUD (create, read, update, delete) functionality for relational databases. It is a lot faster and less complex than Datamapper ORM implementations. See TRADEOFFS.md.
Documentation: https://docs.symlex.org/en/latest/doctrine-active-record/
Basic Example
Usage in REST Controller Context
Doctrine ActiveRecord is perfectly suited for building high-performance REST services.
This example shows how to work with the EntityModel in a REST controller context. Note, how easy it is to avoid deeply nested structures. User model and form factory (provided by the InputValidation package) are injected as dependencies.
See also: InputValidation for PHP – Easy & secure whitelist validation for input data of any origin
Data Access Objects
DAOs directly deal with database tables and raw SQL, if needed. Doctrine\ActiveRecord\Dao\Dao
is suited to implement custom methods using raw SQL. All DAOs expose the following public methods by default:
createDao(string $name)
: Returns a new DAO instancebeginTransaction()
: Start a database transactioncommit()
: Commit a database transactionrollBack()
: Roll back a database transaction
In addition, Doctrine\ActiveRecord\Dao\EntityDao
offers many powerful methods to easily deal with database table rows:
setData(array $data)
: Set raw data (changes can not be detected, e.g. when calling update())setValues(array $data)
: Set multiple valuessetDefinedValues(array $data)
: Set values that exist in the table schema only (slower than setValues())getValues()
: Returns all values as arrayfind($id)
: Find a row by primary keyreload()
: Reload row values from databasegetValues()
: Returns all values as associative arrayexists($id)
: Returns true, if a row with the given primary key existssave()
: Insert a new rowupdate()
: Updates changed values in the databasedelete()
: Delete entity from databasegetId()
: Returns the ID of the currently loaded record (throws exception, if empty)hasId()
: Returns true, if the DAO instance has an ID assigned (primary key)setId($id)
: Set primary keyfindAll(array $cond = array(), $wrapResult = true)
: Returns all instances that match $cond (use search() or searchAll(), if you want to limit or sort the result set)search(array $params)
: Returns aSearchResult
object (see below for supported parameters)wrapAll(array $rows)
: Create and return a new DAO for each array elementupdateRelationTable(string $relationTable, string $primaryKeyName, string $foreignKeyName, array $existing, array $updated)
: Helper function to update n-to-m relationship tableshasTimestampEnabled()
: Returns true, if this DAO automatically adds timestamps when creating and updating rowsfindList(string $colName, string $order = '', string $where = '', string $indexName = '')
: Returns a key/value array (list) of all matching rowsgetTableName()
: Returns the name of the underlying database tablegetPrimaryKeyName()
: Returns the name of the primary key column (throws an exception, if primary key is an array)
Search Parameters
search() accepts the following optional parameters to limit, filter and sort search results:
table
: Table name
table_alias
: Alias name for "table" (table reference for join and join_left)
cond
: Search conditions as array (key/value or just values for raw SQL)
count
: Maximum number of results (integer)
offset
: Result offset (integer)
join
: List of joined tables incl join condition e.g. array(array('u', 'phonenumbers', 'p', 'u.id = p.user_id'))
, see Doctrine DBAL manual
left_join
: See join
columns
: List of columns (array)
order
: Sort order (if not false)
group
: Group by (if not false)
wrap
: If false, raw arrays are returned instead of DAO instances
ids_only
: Return primary key values only
sql_filter
: Raw SQL filter (WHERE)
id_filter
: If not empty, limit result to this list of primary key IDs
Search Result
When calling search()
on a EntityDao
or EntityModel
, you'll get a SearchResult
instance as return value.
It implements ArrayAccess
, Serializable
, IteratorAggregate
and Countable
and can be used either as array
or object with the following methods:
getAsArray()
: Returns search result as array
getSortOrder()
: Returns sort order as string
getSearchCount()
: Returns search count (limit) as integer
getSearchOffset()
: Returns search offset as integer
getResultCount()
: Returns the number of actual query results (<= limit)
getTotalCount()
: Returns total result count (in the database)
getAllResults()
: Returns all results as array of EntityDao
or EntityModel
instances
getAllResultsAsArray()
: Returns all results as nested array (e.g. to serialize it as JSON)
getFirstResult()
: Returns first result EntityDao
or EntityModel
instance or throws an exception
Entity Configuration
DAO entities are configured using protected class properties:
Possible values for $_formatMap are defined as constants in Doctrine\ActiveRecord\Dao\Format
:
Example:
Business Models
Business Models are logically located between Controllers - which render views and validate user input - and Data Access Objects (DAOs), that are low-level interfaces to a storage backend or Web service.
Public interfaces of models are high-level and should reflect all use cases within their domain. There are a number of standard use-cases that are pre-implemented in the base class Doctrine\ActiveRecord\Model\EntityModel
:
createModel(string $name = '', Dao $dao = null)
: Create a new model instance
find($id)
: Find a record by primary key
reload()
: Reload values from database
findAll(array $cond = array(), $wrapResult = true)
: Find multiple records; if $wrapResult
is false, plain DAOs are returned instead of model instances
search(array $cond, array $options = array())
: Returns a SearchResult
object ($options can contain count, offset, sort order etc, see search() in the DAO documentation above)
searchAll(array $cond = array(), $order = false)
: Simple version of search(), similar to findAll()
searchOne(array $cond = array())
: Search a single record; throws an exception if 0 or more than one record are found
searchIds(array $cond, array $options = array())
: Returns an array of matching primary keys for the given search condition
getModelName()
: Returns the model name without prefix and postfix
getId()
: Returns the ID of the currently loaded record (throws exception, if empty)
hasId()
: Returns true, if the model instance has an ID assigned (primary key)
getValues()
: Returns all model properties as associative array
getEntityTitle()
: Returns the common name of this entity
isDeletable()
: Returns true, if the model instance can be deleted with delete()
isUpdatable()
: Returns true, if the model instance can be updated with update($values)
isCreatable()
: Returns true, if new entities can be created in the database with create($values)
batchEdit(array $ids, array $properties)
: Update data for multiple records
getTableName()
: Returns the name of the associated main database table
hasTimestampEnabled()
: Returns true, if timestamps are enabled for the associated DAO
delete()
: Permanently delete the entity record from the database
save(array $values)
: Create a new record using the values provided
update(array $values)
: Update model instance database record; before assigning multiple values to a model instance, data should be validated using a form class
How much validation should be implemented within a model? Wherever invalid data can lead to security issues or major inconsistencies, some core validation rules must be implemented in the model layer. Model exception messages usually don’t require translation (in multilingual applications), since invalid values should be recognized beforehand by a form class. If you expect certain exceptions, you should catch and handle them in your controllers.
Models are associated with their respective Dao using a protected class property:
Example:
Unit Tests
This library comes with a docker-compose.yml
file for MySQL and database fixtures to run unit tests (MySQL will bind to 127.0.0.1:3308):
Composer
To use this library in your project, simply run composer require symlex/doctrine-active-record
or
add "symlex/doctrine-active-record" to your composer.json file and run composer update
:
About
Doctrine ActiveRecord is maintained by Michael Mayer. Feel free to send an e-mail to [email protected] if you have any questions, need commercial support or just want to say hello. We welcome contributions of any kind. If you have a bug or an idea, read our guide before opening an issue.
Note: This library is part of Symlex (a framework stack for agile Web development based on Symfony) and not an official Doctrine project.