Commit f2e9aa91 authored by jwage's avatar jwage

[2.0] Cleaning up old stuff.

parent 9dcab5ee

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

Beta 3
------
* r3323: Added Doctrine_Record and Doctrine_Collection synchronizeWithArray method
* r3264: Added a $deep parameter to Doctrine_Record::refresh()
Beta 2
------
* r3183: NestedSet: 'level' column renamed to 'lvl' because LEVEL is an oracle keyword.
In order to upgrade existing trees you need to rename the level column to lvl
in your databases. This does not affect your code because the NestedSet now uses
a column alias (lvl as level). So your code still refers to the 'level' field.
* r3048: Doctrine::exportSchema() replaced by Doctrine::createTablesFromModels()
* r3048: Doctrine::exportSql() replaced by Doctrine::generateSqlFromModels()
* r3048: Doctrine::importSchema() replaced by Doctrine::generateModelsFromDb()
* r3048: loadAll() loadAllRuntimeClasses() removed
Beta 1
------
+ Query Language
deny from all
\ No newline at end of file
+ Introduction
+ Getting started
+ Connection management
+ Basic schema mapping
+ Relations
+ Working with objects
+ Component overview
+ Hierarchical data
+ Configuration
+ DQL (Doctrine Query Language)
+ Native SQL
+ Transactions
+ Caching
+ Event listeners
+ Class templates
+ Plugins
+ File parser
+ Migration
+ Data fixtures
+ Schema Files
+ Searching
+ Database abstraction
+ Improving Performance
+ Technology
+ Exceptions and warnings
+ Real world examples
+ Coding standards
+ Utilities
\ No newline at end of file
<code type="php">
class Customer extends Doctrine_Record {
public function setUp() {
// setup code goes here
}
public function setTableDefinition() {
// table definition code goes here
}
public function getAvailibleProducts() {
// some code
}
public function setName($name) {
if($this->isValidName($name))
$this->set("name",$name);
}
public function getName() {
return $this->get("name");
}
}
</code>
<code type="php">
// custom primary key column name
class Group extends Doctrine_Record {
public function setUp() {
$this->setPrimaryKeyColumn("group_id");
}
}
</code>
* Doctrine::ATTR_LISTENER
* Doctrine::ATTR_FETCHMODE = 2;
* Doctrine::ATTR_CACHE_DIR = 3;
* Doctrine::ATTR_CACHE_TTL = 4;
* Doctrine::ATTR_CACHE_SIZE = 5;
* Doctrine::ATTR_CACHE_SLAM = 6;
* Doctrine::ATTR_CACHE = 7;
* Doctrine::ATTR_BATCH_SIZE = 8;
* Doctrine::ATTR_PK_COLUMNS = 9;
/**
* primary key type attribute
*/
* Doctrine::ATTR_PK_TYPE = 10;
/**
* locking attribute
*/
* Doctrine::ATTR_LOCKMODE = 11;
/**
* validatate attribute
*/
* Doctrine::ATTR_VLD = 12;
/**
* name prefix attribute
*/
* Doctrine::ATTR_NAME_PREFIX = 13;
/**
* create tables attribute
*/
* Doctrine::ATTR_CREATE_TABLES = 14;
/**
* collection key attribute
*/
* Doctrine::ATTR_COLL_KEY = 15;
/**
* collection limit attribute
*/
* Doctrine::ATTR_COLL_LIMIT = 16;
<code type="php">
class Email extends Doctrine_Record {
public function setUp() {
$this->setAttribute(Doctrine::ATTR_LISTENER,new MyListener());
}
public function setTableDefinition() {
$this->hasColumn("address","string",150,"email|unique");
}
}
</code>
<code type="php">
// setting default fetchmode
// availible fetchmodes are Doctrine::FETCH_LAZY, Doctrine::FETCH_IMMEDIATE and Doctrine::FETCH_BATCH
// the default fetchmode is Doctrine::FETCH_LAZY
class Address extends Doctrine_Record {
public function setUp() {
$this->setAttribute(Doctrine::ATTR_FETCHMODE,Doctrine::FETCH_IMMEDIATE);
}
}
</code>
<code type="php">
// using sequences
class User extends Doctrine_Record {
public function setUp() {
$this->setSequenceName("user_seq");
}
}
</code>
<code type="php">
$q = new Doctrine_Query();
$q->from('User')->where('User.Phonenumber.phonenumber.contains(?,?,?)');
$users = $q->execute(array('123 123 123', '0400 999 999', '+358 100 100'));
</code>
<code type="php">
$q = new Doctrine_Query();
$q->from('User')->where('User.Phonenumber.phonenumber.like(?,?)');
$users = $q->execute(array('%123%', '456%'));
</code>
<code type="php">
$q = new Doctrine_Query();
$q->from('User')->where('User.Phonenumber.phonenumber.regexp(?,?)');
$users = $q->execute(array('[123]', '^[3-5]'));
</code>
*
NOT, !
Logical NOT. Evaluates to 1 if the
operand is 0, to 0 if
the operand is non-zero, and NOT NULL
returns NULL.
<b class='title'>DQL condition :** NOT 10
-&gt; 0
<b class='title'>DQL condition :** NOT 0
-&gt; 1
<b class='title'>DQL condition :** NOT NULL
-&gt; NULL
<b class='title'>DQL condition :** ! (1+1)
-&gt; 0
<b class='title'>DQL condition :** ! 1+1
-&gt; 1
</pre>
The last example produces 1 because the
expression evaluates the same way as
( ! 1)+1.
*
<a name="function_and"></a>
<a class="indexterm" name="id2965271"></a>
<a class="indexterm" name="id2965283"></a>
AND
Logical AND. Evaluates to 1 if all
operands are non-zero and not NULL, to
0 if one or more operands are
0, otherwise NULL is
returned.
<b class='title'>DQL condition :** 1 AND 1
-&gt; 1
<b class='title'>DQL condition :** 1 AND 0
-&gt; 0
<b class='title'>DQL condition :** 1 AND NULL
-&gt; NULL
<b class='title'>DQL condition :** 0 AND NULL
-&gt; 0
<b class='title'>DQL condition :** NULL AND 0
-&gt; 0
</pre>
*
OR
Logical OR. When both operands are
non-NULL, the result is
1 if any operand is non-zero, and
0 otherwise. With a
NULL operand, the result is
1 if the other operand is non-zero, and
NULL otherwise. If both operands are
NULL, the result is
NULL.
<b class='title'>DQL condition :** 1 OR 1
-&gt; 1
<b class='title'>DQL condition :** 1 OR 0
-&gt; 1
<b class='title'>DQL condition :** 0 OR 0
-&gt; 0
<b class='title'>DQL condition :** 0 OR NULL
-&gt; NULL
<b class='title'>DQL condition :** 1 OR NULL
-&gt; 1
</pre>
*
<a name="function_xor"></a>
<a class="indexterm" name="id2965520"></a>
XOR
Logical XOR. Returns NULL if either
operand is NULL. For
non-NULL operands, evaluates to
1 if an odd number of operands is
non-zero, otherwise 0 is returned.
<b class='title'>DQL condition :** 1 XOR 1
-&gt; 0
<b class='title'>DQL condition :** 1 XOR 0
-&gt; 1
<b class='title'>DQL condition :** 1 XOR NULL
-&gt; NULL
<b class='title'>DQL condition :** 1 XOR 1 XOR 1
-&gt; 1
</pre>
a XOR b is mathematically equal to
(a AND (NOT b)) OR ((NOT a) and b).
<code type="php">
$sess = Doctrine_Manager::getInstance()->openConnection(new PDO("dsn","username","password"));
// select first ten rows starting from the row 20
$sess->select("select * from user",10,20);
</code>
<code type="php">
try {
$conn->beginTransaction();
$user->save();
$conn->beginTransaction();
$group->save();
$email->save();
$conn->commit();
$conn->commit();
} catch(Exception $e) {
$conn->rollback();
}
</code>
<code type="php">
// works only if you use doctrine database handler
$dbh = $conn->getDBH();
$times = $dbh->getExecTimes();
// print all executed queries and their execution times
foreach($dbh->getQueries() as $index => $query) {
print $query." ".$times[$index];
}
</code>
<code type="php">
$sess = Doctrine_Manager::getInstance()->openConnection(new PDO("dsn","username","password"));
// gets the next ID from a sequence
$sess->getNextID($sequence);
</code>
<code type="php">
$sess = Doctrine_Manager::getInstance()->openConnection(new PDO("dsn","username","password"));
try {
$sess->beginTransaction();
// some database operations
$sess->commit();
} catch(Exception $e) {
$sess->rollback();
}
</code>
Doctrine supports aggregates and composites. When binding composites you can use methods Doctrine_Record::ownsOne() and Doctrine_Record::ownsMany(). When binding
aggregates you can use methods Doctrine_Record::hasOne() and Doctrine_Record::hasMany(). Basically using the owns* methods is like adding a database level ON CASCADE DELETE
constraint on related component with an exception that doctrine handles the deletion in application level.
In Doctrine if you bind an Email to a User using ownsOne or ownsMany methods, everytime User record calls delete the associated
Email record is also deleted.
Then again if you bind an Email to a User using hasOne or hasMany methods, everytime User record calls delete the associated
Email record is NOT deleted.
Doctrine_Association represents a many-to-many association between database tables.
Doctrine_Collection is a collection of Data Access Objects. Doctrine_Collection represents a record set.
Doctrine_Collection_Batch is a Doctrine_Collection with batch fetching strategy.
Doctrine_Collection_Immediate is a Doctrine_Collection with immediate fetching strategy.
Doctrine_Collection_Lazy is a Doctrine_Collection with lazy fetching strategy.
Doctrine_ForeignKey represents a one-to-many association or one-to-one association between two database tables.
Doctrine_Manager is the base component of Doctrine ORM framework. Doctrine_Manager is a colletion of Doctrine_Connections. All the new connections are being
opened by Doctrine_Manager::openConnection().
Doctrine_Record is a wrapper for database row.
<code type="php">
$user = $table->find(2);
// get state
$state = $user->getState();
print $user->name;
print $user["name"];
print $user->get("name");
$user->name = "Jack Daniels";
$user->set("name","Jack Daniels");
// serialize record
$serialized = serialize($user);
$user = unserialize($serialized);
// create a copy
$copy = $user->copy();
// get primary key
$id = $user->getID();
// print lots of useful info
print $user;
// save all the properties and composites
$user->save();
// delete this data access object and related objects
$user->delete();
</code>
Doctrine_Connection is a wrapper for database connection. It creates Doctrine_Tables and keeps track of all the created tables.
Doctrine_Connection provides things that are missing from PDO like sequence support and limit/offset emulation.
<code type="php">
$sess = $manager->openConnection(Doctrine_Db::getConnection("schema://username:password@hostname/database"));
// get connection state:
switch($sess):
case Doctrine_Connection::STATE_BUSY:
// multiple open transactions
break;
case Doctrine_Connection::STATE_ACTIVE:
// one open transaction
break;
case Doctrine_Connection::STATE_CLOSED:
// closed state
break;
case Doctrine_Connection::STATE_OPEN:
// open state and zero open transactions
break;
endswitch;
// getting database handler
$dbh = $sess->getDBH();
// flushing the connection
$sess->flush();
// print lots of useful info about connection:
print $sess;
</code>
Doctrine_Table creates records and holds info of all foreign keys and associations. Doctrine_Table
represents a database table.
A foreign key constraint specifies that the values in a column (or a group of columns) must match the values appearing in some row of another table.
In other words foreign key constraints maintain the referential integrity between two related tables.
Whenever you fetch records with eg. Doctrine_Table::findAll or Doctrine_Connection::query methods an instance of
Doctrine_Collection is returned. There are many types of collections in Doctrine and it is crucial to understand
the differences of these collections. Remember choosing the right fetching strategy (collection type) is one of the most
influental things when it comes to boosting application performance.
* Immediate Collection
Fetches all records and all record data immediately into collection memory. Use this collection only if you really need to show all that data
in web page.
Example query:
SELECT id, name, type, created FROM user
* Batch Collection
Fetches all record primary keys into colletion memory. When individual collection elements are accessed this collection initializes proxy objects.
When the non-primary-key-property of a proxy object is accessed that object sends request to Batch collection which loads the data
for that specific proxy object as well as other objects close to that proxy object.
Example queries:
SELECT id FROM user
SELECT id, name, type, created FROM user WHERE id IN (1,2,3,4,5)
SELECT id, name, type, created FROM user WHERE id IN (6,7,8,9,10)
[ ... ]
* Lazy Collection
Lazy collection is exactly same as Batch collection with batch size preset to one.
Example queries:
SELECT id FROM user
SELECT id, name, type, created FROM user WHERE id = 1
SELECT id, name, type, created FROM user WHERE id = 2
SELECT id, name, type, created FROM user WHERE id = 3
[ ... ]
* Offset Collection
Offset collection is the same as immediate collection with the difference that it uses database provided limiting of queries.
Example queries:
SELECT id, name, type, created FROM user LIMIT 5
SELECT id, name, type, created FROM user LIMIT 5 OFFSET 5
SELECT id, name, type, created FROM user LIMIT 5 OFFSET 10
[ ... ]
<code type="php">
$table = $conn->getTable("User");
$table->setAttribute(Doctrine::ATTR_FETCHMODE, Doctrine::FETCH_IMMEDIATE);
$users = $table->findAll();
// or
$users = $conn->query("FROM User-I"); // immediate collection
foreach($users as $user) {
print $user->name;
}
$table->setAttribute(Doctrine::ATTR_FETCHMODE, Doctrine::FETCH_LAZY);
$users = $table->findAll();
// or
$users = $conn->query("FROM User-L"); // lazy collection
foreach($users as $user) {
print $user->name;
}
$table->setAttribute(Doctrine::ATTR_FETCHMODE, Doctrine::FETCH_BATCH);
$users = $table->findAll();
// or
$users = $conn->query("FROM User-B"); // batch collection
foreach($users as $user) {
print $user->name;
}
$table->setAttribute(Doctrine::ATTR_FETCHMODE, Doctrine::FETCH_OFFSET);
$users = $table->findAll();
// or
$users = $conn->query("FROM User-O"); // offset collection
foreach($users as $user) {
print $user->name;
}
</code>
<code type="php">
$q = new Doctrine_Query();
$q->from('User(COUNT(id))');
// returns an array
$a = $q->execute();
// selecting multiple aggregate values:
$q = new Doctrine_Query();
$q->from('User(COUNT(id)).Phonenumber(MAX(phonenumber))');
$a = $q->execute();
</code>
<code type="php">
$query->from("User")
->where("User.name = ?");
$query->execute(array('Jack Daniels'));
</code>
<?php
/**
$str = "
The following examples should give a hint of how DQL is converted into SQL.
The classes used in here are the same as in chapter 14.1 (Users and groups are both entities etc).
DQL QUERY: FROM Email WHERE Email.address LIKE '%@example%'
SQL QUERY: SELECT email.id AS Email__id FROM email WHERE (email.address LIKE '%@example%')
DQL QUERY: FROM User(id) WHERE User.Phonenumber.phonenumber LIKE '%123%'
SQL QUERY: SELECT entity.id AS entity__id FROM entity LEFT JOIN phonenumber ON entity.id = phonenumber.entity_id WHERE phonenumber.phonenumber LIKE '%123%' AND (entity.type = 0)
DQL QUERY: FROM Forum_Board(id).Threads(id).Entries(id)
SQL QUERY: SELECT forum_board.id AS forum_board__id, forum_thread.id AS forum_thread__id, forum_entry.id AS forum_entry__id FROM forum_board LEFT JOIN forum_thread ON forum_board.id = forum_thread.board_id LEFT JOIN forum_entry ON forum_thread.id = forum_entry.thread_id
DQL QUERY: FROM User(id) WHERE User.Group.name = 'Action Actors'
SQL QUERY: SELECT entity.id AS entity__id FROM entity LEFT JOIN groupuser ON entity.id = groupuser.user_id LEFT JOIN entity AS entity2 ON entity2.id = groupuser.group_id WHERE entity2.name = 'Action Actors' AND (entity.type = 0 AND (entity2.type = 1 OR entity2.type IS NULL))
DQL QUERY: FROM User(id) WHERE User.Group.Phonenumber.phonenumber LIKE '123 123'
SQL QUERY: SELECT entity.id AS entity__id FROM entity LEFT JOIN groupuser ON entity.id = groupuser.user_id LEFT JOIN entity AS entity2 ON entity2.id = groupuser.group_id LEFT JOIN phonenumber ON entity2.id = phonenumber.entity_id WHERE phonenumber.phonenumber LIKE '123 123' AND (entity.type = 0 AND (entity2.type = 1 OR entity2.type IS NULL))
";
function renderQueries($str) {
$e = explode("\n",$str);
$color = "367FAC";
foreach($e as $line) {
if(strpos($line, "SQL") !== false)
$color = "A50A3D";
elseif(strpos($line, "DQL") !== false)
$color = "367FAC";
$l = str_replace("SELECT","
<font color='$color'>**SELECT**</font>",$line);
$l = str_replace("FROM","
<font color='$color'>**FROM**</font>",$l);
$l = str_replace("LEFT JOIN","
<font color='$color'>**LEFT JOIN**</font>",$l);
$l = str_replace("INNER JOIN","
<font color='$color'>**INNER JOIN**</font>",$l);
$l = str_replace("WHERE","
<font color='$color'>**WHERE**</font>",$l);
$l = str_replace("AS","<font color='$color'>**AS**</font>",$l);
$l = str_replace("ON","<font color='$color'>**ON**</font>",$l);
$l = str_replace("ORDER BY","<font color='$color'>**ORDER BY**</font>",$l);
$l = str_replace("LIMIT","<font color='$color'>**LIMIT**</font>",$l);
$l = str_replace("OFFSET","<font color='$color'>**OFFSET**</font>",$l);
$l = str_replace("DISTINCT","<font color='$color'>**DISTINCT**</font>",$l);
$l = str_replace(" ","<dd>",$l);
print $l."<br>";
if(substr($l,0,3) == "SQL") print "<hr valign='left' class='small'>";
}
}
renderQueries($str);
*/
?>
<code type="php">
// select all users and load the data directly (Immediate fetching strategy)
$coll = $conn->query("FROM User-I");
// or
$coll = $conn->query("FROM User-IMMEDIATE");
// select all users and load the data in batches
$coll = $conn->query("FROM User-B");
// or
$coll = $conn->query("FROM User-BATCH");
// select all user and use lazy fetching
$coll = $conn->query("FROM User-L");
// or
$coll = $conn->query("FROM User-LAZY");
</code>
<code type="php">
// retrieve all users with only their properties id and name loaded
$users = $conn->query("FROM User(id, name)");
</code>
You can overload the query object by calling the dql query parts as methods.
<code type="php">
$conn = Doctrine_Manager::getInstance()->openConnection(new PDO("dsn","username","password"));
$query = new Doctrine_Query($conn);
$query->from("User-b")
->where("User.name LIKE 'Jack%'")
->orderby("User.created")
->limit(5);
$users = $query->execute();
$query->from("User.Group.Phonenumber")
->where("User.Group.name LIKE 'Actors%'")
->orderby("User.name")
->limit(10)
->offset(5);
$users = $query->execute();
</code>
Doctrine provides two relation operators: '.' aka dot and ':' aka colon.
The dot-operator is used for SQL LEFT JOINs and the colon-operator is used
for SQL INNER JOINs. Basically you should use dot operator if you want for example
to select all users and their phonenumbers AND it doesn't matter if the users actually have any phonenumbers.
On the other hand if you want to select only the users which actually have phonenumbers you should use the colon-operator.
<code type="php">
$query->from('User u')->innerJoin('u.Email e');
$query->execute();
// executed SQL query:
// SELECT ... FROM user INNER JOIN email ON ...
$query->from('User u')->leftJoin('u.Email e');
$query->execute();
// executed SQL query:
// SELECT ... FROM user LEFT JOIN email ON ...
</code>
There are three possible ways to access the properties of a record (fields of database row).
You can use overloading, ArrayAccess interface or simply Doctrine_Record::get() method.
**Doctrine_Record objects have always all properties in lowercase**.
++ Introduction
++ Table and class naming
++ Table options
++ Columns
++ Constraints and validators
++ Record identifiers
++ Indexes
+++ Column naming
+++ Column aliases
+++ Default values
+++ Data types
+++ About type conversion
Doctrine offers a way of setting column aliases. This can be very useful when you want to keep the application logic separate from the database logic. For example if you want to change the name of the database field all you need to change at your application is the column definition.
<code type="php">
class Book extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('bookName as name', 'string');
}
}
$book = new Book();
$book->name = 'Some book';
$book->save();
</code>
One problem with database compatibility is that many databases differ in their behaviour of how the result set of a query is returned. MySQL leaves the field names unchanged, which means if you issue a query of the form "SELECT myField FROM ..." then the result set will contain the field 'myField'.
Unfortunately, this is just the way MySql and some other databases do it. Postgres for example returns all field names in lowercase whilst Oracle returns all field names in uppercase. "So what? In what way does this influence me when using Doctrine?", you may ask. Fortunately, you don't have to bother about that issue at all.
Doctrine takes care of this problem transparently. That means if you define a derived Record class and define a field called 'myField' you will always access it through $record->myField (or $record['myField'], whatever you prefer) no matter whether you're using MySQL or Postgres or Oracle etc.
In short: You can name your fields however you want, using under_scores, camelCase or whatever you prefer.
Doctrine supports default values for all data types. When default value is attached to a record column this means two of things.
First this value is attached to every newly created Record.
<code type="php">
class User extends Doctrine_record {
public function setTableDefinition() {
$this->hasColumn('name', 'string', 50, array('default' => 'default name'));
}
}
$user = new User();
print $user->name; // default name
</code>
Also when exporting record class to database DEFAULT //value// is attached to column definition statement.
+++ Introduction
//From [http://www.postgresql.org/docs/8.2/static/ddl-constraints.html PostgreSQL Documentation]://
> Data types are a way to limit the kind of data that can be stored in a table. For many applications, however, the constraint they provide is too coarse. For example, a column containing a product price should probably only accept positive values. But there is no standard data type that accepts only positive numbers. Another issue is that you might want to constrain column data with respect to other columns or rows. For example, in a table containing product information, there should be only one row for each product number.
Doctrine allows you to define *portable* constraints on columns and tables. Constraints give you as much control over the data in your tables as you wish. If a user attempts to store data in a column that would violate a constraint, an error is raised. This applies even if the value came from the default value definition.
Doctrine constraints act as database level constraints as well as application level validators. This means double security: the database doesn't allow wrong kind of values and neither does the application.
Here is a full list of available validators within Doctrine:
|| validator(arguments) || constraints || description ||
|| notnull || NOT NULL || Ensures the 'not null' constraint in both application and database level ||
|| email || || Checks if value is valid email. ||
|| notblank || NOT NULL || Checks if value is not blank. ||
|| notnull || || Checks if value is not null. ||
|| nospace || || Checks if value has no space chars. ||
|| past || CHECK constraint || Checks if value is a date in the past. ||
|| future || || Checks if value is a date in the future. ||
|| minlength(length) || || Checks if value satisfies the minimum length. ||
|| country || || Checks if value is a valid country code. ||
|| ip || || Checks if value is valid IP (internet protocol) address. ||
|| htmlcolor || || Checks if value is valid html color. ||
|| range(min, max) || CHECK constraint || Checks if value is in range specified by arguments. ||
|| unique || UNIQUE constraint || Checks if value is unique in its database table. ||
|| regexp(expression) || || Checks if value matches a given regexp. ||
|| creditcard || || Checks whether the string is a well formated credit card number ||
|| digits(int, frac) || Precision and scale || Checks if given value has //int// number of integer digits and //frac// number of fractional digits ||
+++ Notnull
A not-null constraint simply specifies that a column must not assume the null value. A not-null constraint is always written as a column constraint.
The following definition uses a notnull constraint for column {{name}}. This means that the specified column doesn't accept null values.
<code type="php">
class User extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('name', 'string', 200, array('notnull' => true,
'primary' => true));
}
}
</code>
When this class gets exported to database the following SQL statement would get executed (in MySQL):
<code type="sql">
CREATE TABLE user (name VARCHAR(200) NOT NULL, PRIMARY KEY(name))
</code>
The notnull constraint also acts as an application level validator. This means that if Doctrine validators are turned on, Doctrine will automatically check that specified columns do not contain null values when saved.
If those columns happen to contain null values {{Doctrine_Validator_Exception}} is raised.
+++ Unique
Unique constraints ensure that the data contained in a column or a group of columns is unique with respect to all the rows in the table.
In general, a unique constraint is violated when there are two or more rows in the table where the values of all of the columns included in the constraint are equal. However, two null values are not considered equal in this comparison. That means even in the presence of a unique constraint it is possible to store duplicate rows that contain a null value in at least one of the constrained columns. This behavior conforms to the SQL standard, but some databases do not follow this rule. So be careful when developing applications that are intended to be portable.
The following definition uses a unique constraint for column {{name}}.
<code type="php">
class User extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('name', 'string', 200, array('unique' => true));
}
}
</code>
>> Note: You should only use unique constraints for other than primary key columns. Primary key columns are always unique.
+++ Check
Some of the Doctrine validators also act as database level check constraints. When a record with these validators is exported additional CHECK constraints are being added to CREATE TABLE statement.
Consider the following example which uses 'min' validator:
<code type="php">
class Product extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('id', 'integer', 4, 'primary');
$this->hasColumn('price', 'decimal', 18, array('min' => 0));
}
}
</code>
When exported the given class definition would execute the following statement (in pgsql):
<code type="sql">
CREATE TABLE product (
id INTEGER,
price NUMERIC,
PRIMARY KEY(id),
CHECK (price >= 0))
</code>
So Doctrine optionally ensures even at the database level that the price of any product cannot be below zero.
You can also set the maximum value of a column by using the 'max' validator. This also creates the equivalent CHECK constraint.
<code type="php">
class Product extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('id', 'integer', 4, 'primary');
$this->hasColumn('price', 'decimal', 18, array('min' => 0, 'max' => 1000000));
}
}
</code>
Generates (in pgsql):
<code type="sql">
CREATE TABLE product (
id INTEGER,
price NUMERIC,
PRIMARY KEY(id),
CHECK (price >= 0),
CHECK (price <= 1000000))
</code>
Lastly you can create any kind of CHECK constraints by using the check() method of the Doctrine_Record. In the last example we add constraint to ensure that price is always higher than the discounted price.
<code type="php">
class Product extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('id', 'integer', 4, 'primary');
$this->hasColumn('price', 'decimal', 18, array('min' => 0, 'max' => 1000000));
$this->hasColumn('discounted_price', 'decimal', 18, array('min' => 0, 'max' => 1000000));
$this->check('price > discounted_price');
}
}
</code>
Generates (in pgsql):
<code type="sql">
CREATE TABLE product (
id INTEGER,
price NUMERIC,
PRIMARY KEY(id),
CHECK (price >= 0),
CHECK (price <= 1000000),
CHECK (price > discounted_price))
</code>
> NOTE: some databases don't support CHECK constraints. When this is the case Doctrine simple skips the creation of check constraints.
If the Doctrine validators are turned on the given definition would also ensure that when a record is being saved its price is always greater than zero.
If some of the prices of the saved products within a transaction is below zero, Doctrine throws Doctrine_Validator_Exception and automatically rolls back the transaction.
+++ Introduction
Indexes are used to find rows with specific column values quickly. Without an index, the database must begin with the first row and then read through the entire table to find the relevant rows.
The larger the table, the more this consumes time. If the table has an index for the columns in question, the database can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading rows one-by-one.
Indexes come with a cost as they slow down the inserts and updates. However, in general you should **always** use indexes for the fields that are used in SQL where conditions.
+++ Adding indexes
You can add indexes by simple calling {{Doctrine_Record::index('indexName', $definition)}} where {{$definition}} is the definition array.
An example of adding a simple index to field called {{name}}:
<code type="php">
class IndexTest extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('name', 'string');
$this->index('myindex', array('fields' => 'name'));
}
}
</code>
An example of adding a multi-column index to field called {{name}}:
<code type="php">
class MultiColumnIndexTest extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('name', 'string');
$this->hasColumn('code', 'string');
$this->index('myindex', array('fields' => array('name', 'code')));
}
}
</code>
An example of adding a multiple indexes on same table:
<code type="php">
class MultipleIndexTest extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('name', 'string');
$this->hasColumn('code', 'string');
$this->hasColumn('age', 'integer');
$this->index('myindex', array('fields' => array('name', 'code')));
$this->index('ageindex', array('fields' => array('age'));
}
}
</code>
+++ Index options
Doctrine offers many index options, some of them being db-specific. Here is a full list of available options:
<code>
sorting => string('ASC' / 'DESC')
what kind of sorting does the index use (ascending / descending)
length => integer
index length (only some drivers support this)
primary => boolean(true / false)
whether or not the index is primary index
type => string('unique', -- supported by most drivers
'fulltext', -- only availible on Mysql driver
'gist', -- only availible on Pgsql driver
'gin') -- only availible on Pgsql driver
</code>
<code type="php">
class MultipleIndexTest extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('name', 'string');
$this->hasColumn('code', 'string');
$this->hasColumn('age', 'integer');
$this->index('myindex', array(
'fields' => array(
'name' =>
array('sorting' => 'ASC',
'length' => 10),
'code'),
'type' => 'unique',
));
}
}
</code>
+++ Special indexes
Doctrine supports many special indexes. These include Mysql FULLTEXT and Pgsql GiST indexes. In the following example we define a Mysql FULLTEXT index for the field 'content'.
<code type="php">
class Article
{
public function setTableDefinition()
{
$this->hasColumn('name', 'string');
$this->hasColumn('content', 'string');
$this->index('content', array('fields' => 'content',
'type' => 'fulltext'));
}
}
</code>
This chapter and its subchapters tell you how to do basic schema mappings with Doctrine. After you've come in terms with the concepts of this chapter you'll know how to:
1. Define columns for your record classes
2. Define table options
3. Define indexes
4. Define basic constraints and validators for columns
All column mappings within Doctrine are being done via the hasColumn() method of the Doctrine_Record. The hasColumn takes 4 arguments:
# **column name** String that specifies the column name and optional alias. This is needed for all columns. If you want to specify an alias for the column name you'll need to use the format '[columnName] as [columnAlias]'
# **column type** String that specifies the column type. See the column types section.
# **column length** Integer that specifies the column length. Some column types depend not only the given portable type but also on the given length. For example type string with length 1000 will be translated into native type TEXT on mysql.
# **column constraints and validators** An array that specifies the list of constraints and validators applied to given column.
Note that validators / column constraints and the column length fields are optional. The length may be omitted by using **null** for the length argument, allowing doctrine to use a default length and permitting a fourth argument for validation or column constraints.
Lets take our first example. The following definition defines a class called Email which refers to a table called 'emails'. The Email class has two columns id (an auto-incremented primary key column) and a string column called address.
Notice how we add two validators / constraints for the address column (notblank and email). The notblank validator assures that the address column isn't blank (so it must not contain space-characters only) whereas the email validator ensures that the address is a valid email address.
<code type="php">
class Email extends Doctrine_Record {
public function setTableDefinition() {
// setting custom table name:
$this->setTableName('emails');
$this->hasColumn('address', // name of the column
'string', // column type
'200', // column length
array('notblank' => true,
'email' => true // validators / constraints
)
);
}
}
</code>
Now lets create an export script for this class:
<code type="php">
require_once('Email.php');
require_once('path-to-Doctrine/Doctrine.php');
require_once('path-to-doctrine/lib/Doctrine.php');
spl_autoload_register(array('Doctrine', 'autoload'));
// in order to export we need a database connection
$manager = Doctrine_Manager::getInstance();
$conn = $manager->openConnection('mysql://user:pass@localhost/test');
$conn->export->exportClasses(array('Email'));
</code>
The script would execute the following sql (we are using Mysql here as the database backend):
<code>
CREATE TABLE emails (id INT NOT NULL AUTO_INCREMENT, address VARCHAR(200) NOT NULL)
</code>
+++ Introduction
Doctrine supports many kind of identifiers. For most cases it is recommended not to specify any primary keys (Doctrine will then use field name {{id}} as an autoincremented primary key). When using table creation Doctrine is smart enough to emulate the autoincrementation with sequences and triggers on databases that doesn't support it natively.
+++ Natural
Natural identifier is a property or combination of properties that is unique and non-null. The use of natural identifiers is encouraged.
<code type="php">
class User extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('name', 'string', 200, array('primary' => true));
}
}
</code>
+++ Autoincremented
Autoincrement primary key is the most basic identifier and its usage is strongly encouraged. Sometimes you may want to use some other name than {{id}} for your autoinc primary key. It can be specified as follows:
<code type="php">
class User extends Doctrine_Record {
public function setTableDefinition() {
$this->hasColumn('uid', 'integer', 20, array('primary' => true, 'autoincrement' => true));
}
}
</code>
You should consider using autoincremented or sequential primary keys only when the record cannot be identified naturally (in other words it doesn't have a natural identifier).
The following example shows why natural identifiers are more efficient.
Consider three classes Permission, Role and RolePermission. Roles having many permissions and vice versa (so their relation is many-to-many). Now lets also assume that each role and permission are naturally identified by their names.
Now adding autoincremented primary keys to these classes would be simply stupid. It would require more data and it would make the queries more inefficient. For example fetching all permissions for role 'Admin' would be done as follows (when using autoinc pks):
<code type="sql">
SELECT p.*
FROM Permission p
LEFT JOIN RolePermission rp ON rp.permission_id = p.id
LEFT JOIN Role r ON rp.role_id = r.id
WHERE r.name = 'Admin'
</code>
Now remember sql JOINS are always expensive and here we are using two of those. When using natural identifiers the query would look like:
<code type="sql">
SELECT p.*
FROM Permission p
LEFT JOIN RolePermission rp ON rp.permission_name = p.name
WHERE rp.role_name = 'Admin'
</code>
Thats -1 JOIN !
+++ Composite
Composite primary key can be used efficiently in association tables (tables that connect two components together). It is not recommended to use composite primary keys in anywhere else as Doctrine does not support mapping relations on multiple columns.
Due to this fact your doctrine-based system will scale better if it has autoincremented primary key even for association tables.
<code type="php">
class Groupuser extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('user_id', 'integer', 20, array('primary' => true));
$this->hasColumn('group_id', 'integer', 20, array('primary' => true));
}
}
</code>
+++ Sequence
Doctrine supports sequences for generating record identifiers. Sequences are a way of offering unique IDs for data rows. If you do most of your work with e.g. MySQL, think of sequences as another way of doing {{AUTO_INCREMENT}}.
Doctrine knows how to do sequence generation in the background so you don't have to worry about calling database specific queries - Doctrine does it for you, all you need to do is define a column as a sequence column and optionally provide the name of the sequence table and the id column name of the sequence table.
Consider the following record definition:
<code type="php">
class Book extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('id', 'integer', null, array('primary' => true, 'sequence' => true));
$this->hasColumn('name', 'string');
}
}
</code>
By default Doctrine uses the following format for sequence tables {{[tablename]_seq}}. If you wish to change this you can use the following piece of code to change the formatting:
<code type="php">
$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(Doctrine::ATTR_SEQNAME_FORMAT, '%s_my_seq');
</code>
Doctrine uses column named id as the sequence generator column of the sequence table. If you wish to change this globally (for all connections and all tables) you can use the following code:
<code type="php">
$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(Doctrine::ATTR_SEQCOL_NAME, 'my_seq_column');
</code>
In the following example we do not wish to change global configuration we just want to make the {{id}} column to use sequence table called {{book_sequence}}. It can be done as follows:
<code type="php">
class Book extends Doctrine_Record {
public function setTableDefinition()
{
$this->hasColumn('id', 'integer', null, array('primary', 'sequence' => 'book_sequence'));
$this->hasColumn('name', 'string');
}
}
</code>
Here we take the preceding example a little further: we want to have a custom sequence column. Here it goes:
<code type="php">
class Book extends Doctrine_Record {
public function setTableDefinition()
{
$this->hasColumn('id', 'integer', null, array('primary', 'sequence' => array('book_sequence', 'sequence')));
$this->hasColumn('name', 'string');
}
}
</code>
Doctrine automatically creates table names from the record class names. For this reason, it is recommended to name your record classes using the following rules:
* Use {{CamelCase}} naming
* Underscores are allowed
* The first letter must be capitalized
* The class name cannot be one of the following (these keywords are reserved in DQL API):
* {{ALL}}, {{AND}}, {{ANY}}, {{AS}}, {{ASC}}, {{AVG}}, {{BETWEEN}}, {{BIT_LENGTH}}, {{BY}}, {{CHARACTER_LENGTH}}, {{CHAR_LENGTH}}, {{COUNT}}, {{CURRENT_DATE}}, {{CURRENT_TIME}}, {{CURRENT_TIMESTAMP}}, {{DELETE}}, {{DESC}}, {{DISTINCT}}, {{EMPTY}}, {{EXISTS}}, {{FALSE}}, {{FETCH}}, {{FROM}}, {{GROUP}}, {{HAVING}}, {{IN}}, {{INDEXBY}}, {{INNER}}, {{IS}}, {{JOIN}}, {{LEFT}}, {{LIKE}}, {{LOWER}}, {{MAX}}, {{MEMBER}}, {{MIN}}, {{MOD}}, {{NEW}}, {{NOT}}, {{NULL}}, {{OBJECT}}, {{OF}}, {{OR}}, {{ORDER}}, {{OUTER}}, {{POSITION}}, {{SELECT}}, {{SOME}}, {{SUM}}, {{TRIM}}, {{TRUE}}, {{UNKNOWN}}, {{UPDATE}}, {{UPPER}} and {{WHERE}}.
**Example:** {{My_PerfectClass}}
If you need to use a different naming schema, you can override this using the {{setTableName()}} method in the {{setTableDefinition()}} method.
Doctrine offers various table options. All table options can be set via {{Doctrine_Record::option($optionName, $value)}}.
For example if you are using MySQL and want to use INNODB tables it can be done as follows:
<code type="php">
class MyInnoDbRecord extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('name', 'string');
$this->option('type', 'INNODB');
}
}
</code>
In the following example we set the collate and character set options:
<code type="php">
class MyCustomOptionRecord extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('name', 'string');
$this->option('collate', 'utf8_unicode_ci');
$this->option('charset', 'utf8');
}
}
</code>
It is worth noting that for certain databases (Firebird, MySql and PostgreSQL) setting the charset option might not be enough for Doctrine to return data properly. For those databases, users are advised to also use the setCharset function of the database connection:
<code type="php">
Doctrine_Manager::connection($name)->setCharset("utf8");
</code>
Doctrine offers the ability to turn off foreign key constraints for specific Models.
<code type="php">
class MyCustomOptionRecord extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('name', 'string');
$this->setAttribute(Doctrine::ATTR_EXPORT, Doctrine::EXPORT_ALL ^ Doctrine::EXPORT_CONSTRAINTS);
}
}
</code>
\ No newline at end of file
++ Introduction
{{Doctrine_Cache}} offers an intuitive and easy-to-use query caching solution. It provides the following things:
* Multiple cache backends to choose from (including Memcached, APC and Sqlite)
* Advanced options for fine-tuning. {{Doctrine_Cache}} has many options for fine-tuning performance.
Initializing a new cache driver instance:
<code type="php">
$cacheDriver = new Doctrine_Cache_Memcache($options);
</code>
++ Drivers
+++ Memcache
Memcache driver stores cache records into a memcached server. Memcached is a high-performance, distributed memory object caching system. In order to use this backend, you need a memcached daemon and the memcache PECL extension.
<code type="php">
// memcache allows multiple servers
$servers = array('host' => 'localhost',
'port' => 11211,
'persistent' => true);
$cacheDriver = new Doctrine_Cache_Memcache(array('servers' => $servers,
'compression' => false));
</code>
Available options for Memcache driver:
||~ Option ||~ Data Type ||~ Default Value ||~ Description ||
|| servers || array || array(array('host' => 'localhost','port' => 11211, 'persistent' => true)) || An array of memcached servers ; each memcached server is described by an associative array : 'host' => (string) : the name of the memcached server, 'port' => (int) : the port of the memcached server, 'persistent' => (bool) : use or not persistent connections to this memcached server ||
|| compression || boolean || false || true if you want to use on-the-fly compression ||
+++ APC
The Alternative PHP Cache (APC) is a free and open opcode cache for PHP. It was conceived of to provide a free, open, and robust framework for caching and optimizing PHP intermediate code.
The APC cache driver of Doctrine stores cache records in shared memory.
<code type="php">
$cacheDriver = new Doctrine_Cache_Apc();
</code>
+++ Db
Db caching backend stores cache records into given database. Usually some fast flat-file based database is used (such as sqlite).
Initializing sqlite cache driver can be done as above:
<code type="php">
$conn = Doctrine_Manager::connection(new PDO('sqlite::memory:'));
$cacheDriver = new Doctrine_Cache_Sqlite(array('connection' => $conn));
</code>
++ Query Cache & Result Cache
+++ Introduction
Doctrine provides means for caching the results of the DQL parsing process, as well as the end results of DQL queries (the data). These two caching mechanisms can greatly increase performance. Consider the standard workflow of DQL query execution:
# Init new DQL query
# Parse DQL query
# Build database specific SQL query
# Execute the SQL query
# Build the result set
# Return the result set
Now these phases can be very time consuming, especially phase 4 which sends the query to your database server. When Doctrine query cache is being used only the following phases occur:
# Init new DQL query
# Execute the SQL query (grabbed from the cache)
# Build the result set
# Return the result set
If a DQL query has a valid cache entry the cached SQL query is used, otherwise the phases 2-3 are executed normally and the result of these steps is then stored in the cache.
The query cache has no disadvantages, since you always get a fresh query result. You should therefore always use it in a production environment. That said, you can easily use it during development, too. Whenever you change a DQL query and execute it the first time Doctrine sees that is has been modified and will therefore create a new cache entry, so you dont even need to invalidate the cache. It's worth noting that the effectiveness of the query cache greatly relies on the usage of prepared staments (which are used by Doctrine by default anyway). You should not directly embed dynamic query parts and always use placeholders instead.
When using a result cache things get even better. Then your query process looks as follows (assuming a valid cache entry is found):
# Init new DQL query
# Return the result set
As you can see, the result cache implies the query cache shown previously.
You should always consider using a result cache if the data returned by the query does not need to be up-to-date at any time.
+++ Query Cache
++++ Using the query cache
You can set a connection or manager level query cache driver by using Doctrine::ATTR_QUERY_CACHE. Setting a connection level cache driver means that all queries executed with this connection use the specified cache driver whereas setting a manager level cache driver means that all connections (unless overridden at connection level) will use the given cache driver.
Setting a manager level query cache driver:
<code type="php">
$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(Doctrine::ATTR_QUERY_CACHE, $cacheDriver);
</code>
Setting a connection level cache driver:
<code type="php">
$manager = Doctrine_Manager::getInstance();
$conn = $manager->openConnection('pgsql://user:pass@localhost/test');
$conn->setAttribute(Doctrine::ATTR_QUERY_CACHE, $cacheDriver);
</code>
++++ Fine-tuning
In the previous chapter we used global caching attributes. These attributes can be overriden at the query level. You can override the cache driver by calling useQueryCache with a valid cacheDriver. This rarely makes sense for the query cache but is possible:
<code type="php">
$query = new Doctrine_Query();
$query->useQueryCache(new Doctrine_Cache_Apc());
</code>
+++ Result Cache
++++ Using the result cache
You can set a connection or manager level result cache driver by using Doctrine::ATTR_RESULT_CACHE. Setting a connection level cache driver means that all queries executed with this connection use the specified cache driver whereas setting a manager level cache driver means that all connections (unless overridden at connection level) will use the given cache driver.
Setting a manager level cache driver:
<code type="php">
$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(Doctrine::ATTR_RESULT_CACHE, $cacheDriver);
</code>
Setting a connection level cache driver:
<code type="php">
$manager = Doctrine_Manager::getInstance();
$conn = $manager->openConnection('pgsql://user:pass@localhost/test');
$conn->setAttribute(Doctrine::ATTR_RESULT_CACHE, $cacheDriver);
</code>
Usually the cache entries are valid for only some time. You can set global value for how long the cache entries should be considered valid by using Doctrine::ATTR_RESULT_CACHE_LIFESPAN.
<code type="php">
$manager = Doctrine_Manager::getInstance();
// set the lifespan as one hour (60 seconds * 60 minutes = 1 hour = 3600 secs)
$manager->setAttribute(Doctrine::ATTR_RESULT_CACHE_LIFESPAN, 3600);
</code>
Now as we have set a cache driver for use we can make a DQL query to use it:
<code type="php">
$query = new Doctrine_Query();
// fetch blog titles and the number of comments
$query->select('b.title, COUNT(c.id) count')
->from('Blog b')
->leftJoin('b.Comments c')
->limit(10)
->useResultCache(true);
$entries = $query->execute();
</code>
++++ Fine-tuning
In the previous chapter we used global caching attributes. These attributes can be overriden at the query level. You can override the cache driver by calling useCache with a valid cacheDriver:
<code type="php">
$query = new Doctrine_Query();
$query->useResultCache(new Doctrine_Cache_Apc());
</code>
Also you can override the lifespan attribute by calling setResultCacheLifeSpan():
<code type="php">
$query = new Doctrine_Query();
// set the lifespan as half an hour
$query->setResultCacheLifeSpan(60 * 30);
</code>
There are couple of availible Cache attributes on Doctrine:
* Doctrine::ATTR_CACHE_SIZE
* Defines which cache container Doctrine uses
* Possible values: Doctrine::CACHE_* (for example Doctrine::CACHE_FILE)
* Doctrine::ATTR_CACHE_DIR
* cache directory where .cache files are saved
* the default cache dir is %ROOT%/cachedir, where
%ROOT% is automatically converted to doctrine root dir
* Doctrine::ATTR_CACHE_SLAM
* On very busy servers whenever you start the server or modify files you can create a race of many processes all trying to cache the same file at the same time. This option sets the percentage of processes that will skip trying to cache an uncached file. Or think of it as the probability of a single process to skip caching. For example, setting apc.slam_defense to 75 would mean that there is a 75% chance that the process will not cache an uncached file. So, the higher the setting the greater the defense against cache slams. Setting this to 0 disables this feature
* Doctrine::ATTR_CACHE_SIZE
* Cache size attribute
* Doctrine::ATTR_CACHE_TTL
* How often the cache is cleaned
{{Doctrine_Cache}} offers an intuitive and easy-to-use query caching solution. It provides the following things:
* Multiple cache backends to choose from (including Memcached, APC and Sqlite)
* Manual tuning and/or self-optimization. {{Doctrine_Cache}} knows how to optimize itself, yet it leaves user full freedom of whether or not he/she wants to take advantage of this feature.
* Advanced options for fine-tuning. {{Doctrine_Cache}} has many options for fine-tuning performance.
* Cache hooks itself directly into {{Doctrine_Db}} eventlistener system allowing it to be easily added on-demand.
{{Doctrine_Cache}} hooks into {{Doctrine_Db}} eventlistener system allowing pluggable caching. It evaluates queries and puts {{SELECT}} statements in cache. The caching is based on propabalistics. For example if {{savePropability = 0.1}} there is a 10% chance that a query gets cached.
Now eventually the cache would grow very big, hence Doctrine uses propabalistic cache cleaning. When calling {{Doctrine_Cache::clean()}} with {{cleanPropability = 0.25}} there is a 25% chance of the clean operation being invoked. What the cleaning does is that it first reads all the queries in the stats file and sorts them by the number of times occurred. Then if the size is set to 100 it means the cleaning operation will leave 100 most issued queries in cache and delete all other cache entries.
Initializing a new cache instance:
<code type="php">
$dbh = new Doctrine_Db('mysql:host=localhost;dbname=test', $user, $pass);
$cache = new Doctrine_Cache('memcache');
// register it as a Doctrine_Db listener
$dbh->addListener($cache);
</code>
Now you know how to set up the query cache. In the next chapter you'll learn how to tweak the cache in order to get maximum performance.
Doctrine has very comprehensive and fast caching solution.
Its cache is **always up-to-date**.
In order to achieve this doctrine does the following things:
|| 1. Every Doctrine_Table has its own cache directory. The default is cache/componentname/. All the cache files are saved into that directory.
The format of each cache file is [primarykey].cache.
2. When retrieving records from the database doctrine always tries to hit the cache first.
3. If a record (Doctrine_Record) is retrieved from database or inserted into database it will be saved into cache.
4. When a Data Access Object is deleted or updated it will be deleted from the cache ||
Now one might wonder that this kind of solution won't work since eventually the cache will be a copy of database!
So doctrine does the following things to ensure the cache won't get too big:
|| 1. Every time a cache file is accessed the id of that record will be added into the $fetched property of Doctrine_Cache
2. At the end of each script the Doctrine_Cache destructor will write all these primary keys at the end of a stats.cache file
3. Doctrine does propabalistic cache cleaning. The default interval is 200 page loads (= 200 constructed Doctrine_Managers). Basically this means
that the average number of page loads between cache cleans is 200.
4. On every cache clean stats.cache files are being read and the least accessed cache files
(cache files that have the smallest id occurance in the stats file) are then deleted.
For example if the cache size is set to 200 and the number of files in cache is 300, then 100 least accessed files are being deleted.
Doctrine also clears every stats.cache file. ||
So for every 199 fast page loads there is one page load which suffers a little overhead from the cache cleaning operation.
This diff is collapsed.
++ Overview
++ PHP File Formatting
++ Naming Conventions
++ Coding Style
++ Testing
+++ PHP code demarcation
* PHP code must always be delimited by the full-form, standard PHP tags
* Short tags are never allowed. For files containing only PHP code, the closing tag must always be omitted
+++ Strings
* When a string is literal (contains no variable substitutions), the apostrophe or "single quote" must always used to demarcate the string:
<code type="php">
// literal string
$string = 'something';
</code>
* When a literal string itself contains apostrophes, it is permitted to demarcate the string with quotation marks or "double quotes". This is especially encouraged for SQL statements:
<code type="php">
// string contains apostrophes
$sql = "SELECT id, name FROM people WHERE name = 'Fred' OR name = 'Susan'";
</code>
* Variable substitution is permitted using the following form:
<code type="php">
// variable substitution
$greeting = "Hello $name, welcome back!";
</code>
* Strings may be concatenated using the "." operator. A space must always be added before and after the "." operator to improve readability:
<code type="php">
// concatenation
$framework = 'Doctrine' . ' ORM ' . 'Framework';
</code>
* When concatenating strings with the "." operator, it is permitted to break the statement into multiple lines to improve readability. In these cases, each successive line should be padded with whitespace such that the "."; operator is aligned under the "=" operator:
<code type="php">
// concatenation line breaking
$sql = "SELECT id, name FROM user "
. "WHERE name = ? "
. "ORDER BY name ASC";
</code>
+++ Arrays
* Negative numbers are not permitted as indices.
* An indexed array may be started with any non-negative number, however this is discouraged and it is recommended that all arrays have a base index of 0.
* When declaring indexed arrays with the array construct, a trailing space must be added after each comma delimiter to improve readability.
* It is also permitted to declare multiline indexed arrays using the "array" construct. In this case, each successive line must be padded with spaces.
* When declaring associative arrays with the array construct, it is encouraged to break the statement into multiple lines. In this case, each successive line must be padded with whitespace such that both the keys and the values are aligned:
<code type="php">
$sampleArray = array('Doctrine', 'ORM', 1, 2, 3);
$sampleArray = array(1, 2, 3,
$a, $b, $c,
56.44, $d, 500);
$sampleArray = array('first' => 'firstValue',
'second' => 'secondValue');
</code>
+++ Classes
* Classes must be named by following the naming conventions.
* The brace is always written next line after the class name (or interface declaration).
* Every class must have a documentation block that conforms to the PHPDocumentor standard.
* Any code within a class must be indented four spaces.
* Only one class is permitted per PHP file.
* Placing additional code in a class file is NOT permitted.
This is an example of an acceptable class declaration:
<code type="php">
/**
* Documentation here
*/
class Doctrine_SampleClass
{
// entire content of class
// must be indented four spaces
}
</code>
+++ Functions and methods
* Methods must be named by following the naming conventions.
* Methods must always declare their visibility by using one of the private, protected, or public constructs.
* Like classes, the brace is always written next line after the method name. There is no space between the function name and the opening parenthesis for the arguments.
* Functions in the global scope are strongly discouraged.
* This is an example of an acceptable function declaration in a class:
<code type="php">
/**
* Documentation Block Here
*/
class Foo
{
/**
* Documentation Block Here
*/
public function bar()
{
// entire content of function
// must be indented four spaces
}
}
</code>
* Passing by-reference is permitted in the function declaration only:
<code type="php">
/**
* Documentation Block Here
*/
class Foo
{
/**
* Documentation Block Here
*/
public function bar(&$baz)
{
}
}
</code>
* Call-time pass by-reference is prohibited.
* The return value must not be enclosed in parentheses. This can hinder readability and can also break code if a method is later changed to return by reference.
<code type="php">
/**
* Documentation Block Here
*/
class Foo
{
/**
* WRONG
*/
public function bar() {
return($this->bar);
}
/**
* RIGHT
*/
public function bar()
{
return $this->bar;
}
}
</code>
* Function arguments are separated by a single trailing space after the comma delimiter. This is an example of an acceptable function call for a function that takes three arguments:
<code type="php">
threeArguments(1, 2, 3);
</code>
* Call-time pass by-reference is prohibited. See above for the proper way to pass function arguments by-reference.
* For functions whose arguments permitted arrays, the function call may include the {{array}} construct and can be split into multiple lines to improve readability. In these cases, the standards for writing arrays still apply:
<code type="php">
threeArguments(array(1, 2, 3), 2, 3);
threeArguments(array(1, 2, 3, 'Framework',
'Doctrine', 56.44, 500), 2, 3);
</code>
+++ Control statements
* Control statements based on the {{if}} and {{elseif}} constructs must have a single space before the opening parenthesis of the conditional, and a single space after the closing parenthesis.
* Within the conditional statements between the parentheses, operators must be separated by spaces for readability. Inner parentheses are encouraged to improve logical grouping of larger conditionals.
* The opening brace is written on the same line as the conditional statement. The closing brace is always written on its own line. Any content within the braces must be indented four spaces.
<code type="php">
if ($foo != 2) {
$foo = 2;
}
</code>
* For {{if}} statements that include {{elseif}} or {{else}}, the formatting must be as in these examples:
<code type="php">
if ($foo != 1) {
$foo = 1;
} else {
$foo = 3;
}
if ($foo != 2) {
$foo = 2;
} elseif ($foo == 1) {
$foo = 3;
} else {
$foo = 11;
}
</code>
When ! operand is being used it must use the following formatting:
<code type="php">
if ( ! $foo) {
}
</code>
* Control statements written with the {{switch}} construct must have a single space before the opening parenthesis of the conditional statement, and also a single space after the closing parenthesis.
* All content within the {{switch}} statement must be indented four spaces. Content under each {{case}} statement must be indented an additional four spaces but the breaks must be at the same indentation level as the {{case}} statements.
<code type="php">
switch ($case) {
case 1:
case 2:
break;
case 3:
break;
default:
break;
}
</code>
* The construct default may never be omitted from a switch statement.
+++ Inline documentation
Documentation Format:
* All documentation blocks ("docblocks") must be compatible with the phpDocumentor format. Describing the phpDocumentor format is beyond the scope of this document. For more information, visit: http://phpdoc.org/
Methods:
* Every method, must have a docblock that contains at a minimum:
* A description of the function
* All of the arguments
* All of the possible return values
* It is not necessary to use the {{@access}} tag because the access level is already known from the {{public}}, {{private}}, or {{protected}} construct used to declare the function.
* If a function/method may throw an exception, use {{@throws}}:
* {{@throws exceptionclass [description]}}
+++ Classes
* The Doctrine ORM Framework uses the same class naming convention as PEAR and Zend framework, where the names of the classes directly map to the directories in which they are stored. The root level directory of the Doctrine Framework is the "Doctrine/" directory, under which all classes are stored hierarchially.
* Class names may only contain alphanumeric characters. Numbers are permitted in class names but are discouraged. Underscores are only permitted in place of the path separator, eg. the filename "Doctrine/Table/Exception.php" must map to the class name "Doctrine_Table_Exception".
* If a class name is comprised of more than one word, the first letter of each new word must be capitalized. Successive capitalized letters are not allowed, e.g. a class "XML_Reader" is not allowed while "Xml_Reader" is acceptable.
+++ Interfaces
* Interface classes must follow the same conventions as other classes (see above), however must end with the word "{{Interface}}" (unless the interface is approved not to contain it such as {{Doctrine_Overloadable}}). Some examples:
* {{Doctrine_Db_EventListener_Interface}}
* {{Doctrine_EventListener_Interface}}
+++ Filenames
* For all other files, only alphanumeric characters, underscores, and the dash character ("-") are permitted. Spaces are prohibited.
* Any file that contains any PHP code must end with the extension ".php". These examples show the acceptable filenames for containing the class names from the examples in the section above:
* {{Doctrine/Db.php}}
* {{Doctrine/Connection/Transaction.php}}
* File names must follow the mapping to class names described above.
+++ Functions and methods
* Function names may only contain alphanumeric characters. Underscores are not permitted. Numbers are permitted in function names but are discouraged.
* Function names must always start with a lowercase letter. When a function name consists of more than one word, the first letter of each new word must be capitalized. This is commonly called the "studlyCaps" or "camelCaps" method.
* Verbosity is encouraged. Function names should be as verbose as is practical to enhance the understandability of code.
* For object-oriented programming, accessors for objects should always be prefixed with either "get" or "set". This applies to all classes except for Doctrine_Record which has some accessor methods prefixed with 'obtain' and 'assign'. The reason for this is that since all user defined ActiveRecords inherit {{Doctrine_Record}}, it should populate the get / set namespace as little as possible.
* Functions in the global scope ("floating functions") are NOT permmitted. All static functions should be wrapped in a static class.
+++ Variables
All variables must satisfy the following conditions:
* Variable names may only contain alphanumeric characters. Underscores are not permitted. Numbers are permitted in variable names but are discouraged.
* Variable names must always start with a lowercase letter and follow the "camelCaps" capitalization convention.
* Verbosity is encouraged. Variables should always be as verbose as practical. Terse variable names such as "$i" and "$n" are discouraged for anything other than the smallest loop contexts. If a loop contains more than 20 lines of code, the variables for the indices need to have more descriptive names.
* Within the framework certain generic object variables should always use the following names:
||~ Object type ||~ Variable name ||
|| {{Doctrine_Connection}} || {{$conn}} ||
|| {{Doctrine_Collection}} || {{$coll}} ||
|| {{Doctrine_Manager}} || {{$manager}} ||
|| {{Doctrine_Query}} || {{$query}} ||
|| {{Doctrine_Db}} || {{$db}} ||
* There are cases when more descriptive names are more appropriate (for example when multiple objects of the same class are used in same context), in that case it is allowed to use different names than the ones mentioned.
+++ Constants
Following rules must apply to all constants used within Doctrine framework:
* Constants may contain both alphanumeric characters and the underscore.
* Constants must always have all letters capitalized.
* For readablity reasons, words in constant names must be separated by underscore characters. For example, {{ATTR_EXC_LOGGING}} is permitted but {{ATTR_EXCLOGGING}} is not.
* Constants must be defined as class members by using the "const" construct. Defining constants in the global scope with "define" is NOT permitted.
<code type="php">
class Doctrine_SomeClass
{
const MY_CONSTANT = 'something';
}
print Doctrine_SomeClass::MY_CONSTANT;
</code>
+++ Record columns
* All record columns must be in lowercase
* Usage of _ is encouraged for columns that consist of more than one word
<code type="php">
class User
{
public function setTableDefinition()
{
$this->hasColumn('home_address', 'string');
}
}
</code>
* Foreign key fields must be in format [tablename]_[column]
<code type="php">
class Phonenumber
{
public function setTableDefinition()
{
// this field is a foreign key that points to user(id)
$this->hasColumn('user_id', 'integer');
}
}
</code>
+++ General
For files that contain only PHP code, the closing tag ("{{?>}}") is never permitted. It is not required by PHP. Not including it prevents trailing whitespace from being accidentally injected into the output.
IMPORTANT: Inclusion of arbitrary binary data as permitted by {{__HALT_COMPILER()}} is prohibited from any Doctrine framework PHP file or files derived from them. Use of this feature is only permitted for special installation scripts.
+++ Indentation
Use an indent of 4 spaces, with no tabs.
+++ Maximum line length
The target line length is 80 characters, i.e. developers should aim keep code as close to the 80-column boundary as is practical. However, longer lines are acceptable. The maximum length of any line of PHP code is 120 characters.
+++ Line termination
* Line termination is the standard way for Unix text files. Lines must end only with a linefeed (LF). Linefeeds are represented as ordinal 10, or hexadecimal 0x0A.
* Do not use carriage returns (CR) like Macintosh computers (0x0D).
* Do not use the carriage return/linefeed combination (CRLF) as Windows computers (0x0D, 0x0A).
+++ Writing tests
++++ Classes
* All test classes should be referring to a class or specific testing aspect of some class.
* For example {{Doctrine_Record_TestCase}} is a valid name since its referring to class named {{Doctrine_Record}}.
* {{Doctrine_Record_State_TestCase}} is also a valid name since its referring to testing the state aspect of the {{Doctrine_Record}} class.
* However something like {{Doctrine_PrimaryKey_TestCase}} is not valid since its way too generic.
* Every class should have atleast one {{TestCase}} equivalent
* All testcase classes should inherit {{Doctrine_UnitTestCase}}
++++ Methods
* All methods should support agile documentation; if some method failed it should be evident from the name of the test method what went wrong. Also the test method names should give information of the system they test.
* For example {{Doctrine_Export_Pgsql_TestCase::testCreateTableSupportsAutoincPks()}} is a valid test method name. Just by looking at it we know what it is testing. Also we can run agile documentation tool to get little up-to-date system information.
NOTE: Commonly used testing method naming convention {{TestCase::test[methodName]}} is **not** allowed in Doctrine. So in this case {{Doctrine_Export_Pgsql_TestCase::testCreateTable()}} would not be allowed!
* Test method names can often be long. However the content within the methods should rarely be more than dozen lines long. If you need several assert-calls divide the method into smaller methods.
++++ Assertions
* There should never be assertions within any loops and rarely within functions.
This diff is collapsed.
+++ Introduction
Many web applications have different kinds of lists. The lists may contain data from multiple components (= database tables) and they may have actions such as paging, sorting and setting conditions. {{Doctrine_Hook}} helps building these lists. It has a simple API for building search criteria forms as well as building a DQL query from the 'hooked' parameters.
+++ Building queries
+++ List of parsers
+++ Introduction
[**Note**: The term 'Transaction' doesnt refer to database transactions here but to the general meaning of this term]
[**Note**: This component is in **Alpha State**]
Locking is a mechanism to control concurrency. The two most well known locking strategies are optimistic and pessimistic locking. The following is a short description of these two strategies from which only pessimistic locking is currently supported by Doctrine.
**Optimistic Locking:**
The state/version of the object(s) is noted when the transaction begins. When the transaction finishes the noted state/version of the participating objects is compared to the current state/version. When the states/versions differ the objects have been modified by another transaction and the current transaction should fail. This approach is called 'optimistic' because it is assumed that it is unlikely that several users will participate in transactions on the same objects at the same time.
**Pessimistic Locking:**
The objects that need to participate in the transaction are locked at the moment the user starts the transaction. No other user can start a transaction that operates on these objects while the locks are active. This ensures that the user who starts the transaction can be sure that noone else modifies the same objects until he has finished his work.
Doctrine's pessimistic offline locking capabilities can be used to control concurrency during actions or procedures that take several HTTP request and response cycles and/or a lot of time to complete.
+++ Examples
The following code snippet demonstrates the use of Doctrine's pessimistic offline locking capabilities.
At the page where the lock is requested...
<code type="php">
// Get a locking manager instance
$lockingMngr = new Doctrine_Locking_Manager_Pessimistic();
try
{
// Ensure that old locks which timed out are released
// before we try to acquire our lock
// 300 seconds = 5 minutes timeout
$lockingMngr->releaseAgedLocks(300);
// Try to get the lock on a record
$gotLock = $lockingMngr->getLock(
// The record to lock. This can be any Doctrine_Record
$myRecordToLock,
// The unique identifier of the user who is trying to get the lock
'Bart Simpson'
);
if($gotLock)
{
echo "Got lock!";
// ... proceed
}
else
{
echo "Sorry, someone else is currently working on this record";
}
}
catch(Doctrine_Locking_Exception $dle)
{
echo $dle->getMessage();
// handle the error
}
</code>
At the page where the transaction finishes...
<code type="php">
// Get a locking manager instance
$lockingMngr = new Doctrine_Locking_Manager_Pessimistic();
try
{
if($lockingMngr->releaseLock($myRecordToUnlock, 'Bart Simpson'))
{
echo "Lock released";
}
else
{
echo "Record was not locked. No locks released.";
}
}
catch(Doctrine_Locking_Exception $dle)
{
echo $dle->getMessage();
// handle the error
}
</code>
+++ Planned
* Possibility to release locks of a specific Record type (i.e. releasing all locks on 'User' objects).
+++ Technical Details
The pessimistic offline locking manager stores the locks in the database (therefore 'offline'). The required locking table is automatically created when you try to instantiate an instance of the manager and the ATTR_CREATE_TABLES is set to TRUE. This behaviour may change in the future to provide a centralised and consistent table creation procedure for installation purposes.
+++ Maintainer
Roman Borschel - romanb at #doctrine (freenode)
Don't hesitate to contact me if you have questions, ideas, ect.
+++ Introduction
{{Doctrine_Connection_Profiler}} is an eventlistener for {{Doctrine_Connection}}. It provides flexible query profiling. Besides the SQL strings the query profiles include elapsed time to run the queries. This allows inspection of the queries that have been performed without the need for adding extra debugging code to model classes.
{{Doctrine_Connection_Profiler}} can be enabled by adding it as an eventlistener for {{Doctrine_Connection}}.
<code type="php">
$conn = Doctrine_Manager::connection($dsn);
$profiler = new Doctrine_Connection_Profiler();
$conn->setListener($profiler);
</code>
+++ Basic usage
Perhaps some of your pages is loading slowly. The following shows how to build a complete profiler report from the connection:
<code type="php">
$time = 0;
foreach ($profiler as $event) {
$time += $event->getElapsedSecs();
echo $event->getName() . " " . sprintf("%f", $event->getElapsedSecs()) . "<br>\n";
echo $event->getQuery() . "<br>\n";
$params = $event->getParams();
if( ! empty($params)) {
var_dump($params);
}
}
echo "Total time: " . $time . "<br>\n";
</code>
+++ Advanced usage
+++ Introduction
Validation in Doctrine is a way to enforce your business rules in the model part of the MVC architecture. You can think of this validation as a gateway that needs to be passed right before data gets into the persistent data store. The definition of these business rules takes place at the record level, that means in your active record model classes (classes derived from {{Doctrine_Record}}). The first thing you need to do to be able to use this kind of validation is to enable it globally. This is done through the {{Doctrine_Manager}} (see the code below).
Once you enabled validation, you'll get a bunch of validations automatically:
* **Data type validations**: All values assigned to columns are checked for the right type. That means if you specified a column of your record as type 'integer', Doctrine will validate that any values assigned to that column are of this type. This kind of type validation tries to be as smart as possible since PHP is a loosely typed language. For example 2 as well as "7" are both valid integers whilst "3f" is not. Type validations occur on every column (since every column definition needs a type).
* **Length validation**: As the name implies, all values assigned to columns are validated to make sure that the value does not exceed the maximum length.
<code type="php">
// turning on validation
Doctrine_Manager::getInstance()->setAttribute(Doctrine::ATTR_VALIDATE, Doctrine::VALIDATE_ALL);
</code>
You can combine the following constants by using bitwise operations: VALIDATE_ALL, VALIDATE_TYPES, VALIDATE_LENGTHS,
VALIDATE_CONSTRAINTS, VALIDATE_NONE. For example to enable all validations except length validations you would use:
<code>
VALIDATE_ALL & ~VALIDATE_LENGTHS
</code>
+++ More Validation
The type and length validations are handy but most of the time they're not enough. Therefore Doctrine provides some mechanisms that can be used to validate your data in more detail.
Validators are an easy way to specify further validations. Doctrine has a lot of predefined validators that are frequently needed such as email, country, ip, range and regexp validators. You find a full list of available validators at the bottom of this page. You can specify which validators apply to which column through the 4th argument of the {{hasColumn()}} method. If that is still not enough and you need some specialized validation that is not yet available as a predefined validator you have three options:
* You can write the validator on your own.
* You can propose your need for a new validator to a Doctrine developer.
* You can use validation hooks.
The first two options are advisable if it is likely that the validation is of general use and is potentially applicable in many situations. In that case it is a good idea to implement a new validator. However if the validation is special it is better to use hooks provided by Doctrine:
* {{validate()}} (Executed every time the record gets validated)
* {{validateOnInsert()}} (Executed when the record is new and gets validated)
* {{validateOnUpdate()}} (Executed when the record is not new and gets validated)
If you need a special validation in your active record you can simply override one of these methods in your active record class (a descendant of {{Doctrine_Record}}). Within thess methods you can use all the power of PHP to validate your fields. When a field doesnt pass your validation you can then add errors to the record's error stack. The following code snippet shows an example of how to define validators together with custom validation:
<code type="php">
class User extends Doctrine_Record
{
public function setUp()
{
$this->ownsOne('Email', array('local' => 'email_id'));
}
public function setTableDefinition()
{
// no special validators used only types
// and lengths will be validated
$this->hasColumn('name', 'string', 15);
$this->hasColumn('email_id', 'integer');
$this->hasColumn('created', 'integer', 11);
}
// Our own validation
protected function validate()
{
if ($this->name == 'God') {
// Blasphemy! Stop that! ;-)
// syntax: add(<fieldName>, <error code/identifier>)
$this->getErrorStack()->add('name', 'forbiddenName');
}
}
}
class Email extends Doctrine_Record {
public function setTableDefinition() {
// validators 'email' and 'unique' used
$this->hasColumn("address","string",150, array("email", "unique"));
}
}
</code>
+++ Valid or Not Valid
Now that you know how to specify your business rules in your models, it is time to look at how to deal with these rules in the rest of your application.
++++ Implicit validation
Whenever a record is going to be saved to the persistent data store (i.e. through calling {{$record->save()}}) the full validation procedure is executed. If errors occur during that process an exception of the type {{Doctrine_Validator_Exception}} will be thrown. You can catch that exception and analyze the errors by using the instance method {{Doctine_Validator_Exception::getInvalidRecords()}}. This method returns an ordinary array with references to all records that did not pass validation. You can then further explore the errors of each record by analyzing the error stack of each record. The error stack of a record can be obtained with the instance method {{Doctrine_Record::getErrorStack()}}. Each error stack is an instance of the class {{Doctrine_Validator_ErrorStack}}. The error stack provides an easy to use interface to inspect the errors.
++++ Explicit validation
You can explicitly trigger the validation for any record at any time. For this purpose Doctrine_Record provides the instance method {{Doctrine_Record::isValid()}}. This method returns a boolean value indicating the result of the validation. If the method returns false, you can inspect the error stack in the same way as seen above except that no exception is thrown, so you simply obtain the error stack of the record that didnt pass validation through {{Doctrine_Record::getErrorStack()}}.
The following code snippet shows an example of handling implicit validation which caused a {{Doctrine_Validator_Exception}}.
<code type="php">
try {
$user->name = "this is an example of too long name";
$user->Email->address = "drink@@notvalid..";
$user->save();
} catch(Doctrine_Validator_Exception $e) {
// Note: you could also use $e->getInvalidRecords(). The direct way
// used here is just more simple when you know the records you're dealing with.
$userErrors = $user->getErrorStack();
$emailErrors = $user->Email->getErrorStack();
/* Inspect user errors */
foreach($userErrors as $fieldName => $errorCodes) {
switch ($fieldName) {
case 'name':
// $user->name is invalid. inspect the error codes if needed.
break;
}
}
/* Inspect email errors */
foreach($emailErrors as $fieldName => $errorCodes) {
switch ($fieldName) {
case 'address':
// $user->Email->address is invalid. inspect the error codes if needed.
break;
}
}
}
</code>
+++ Introduction
Database views can greatly increase the performance of complex queries. You can think of them as cached queries. {{Doctrine_View}} provides integration between database views and DQL queries.
+++ Managing views
<code type="php">
$conn = Doctrine_Manager::getInstance()
->openConnection(new PDO("dsn","username","password"));
$query = new Doctrine_Query($conn);
$query->from('User.Phonenumber')->limit(20);
$view = new Doctrine_View($query, 'MyView');
// creating a database view
$view->create();
// dropping the view from the database
$view->drop();
</code>
+++ Using views
<code type="php">
$conn = Doctrine_Manager::getInstance()
->openConnection(new PDO("dsn","username","password"));
$query = new Doctrine_Query($conn);
$query->from('User.Phonenumber')->limit(20);
// hook the query into appropriate view
$view = new Doctrine_View($query, 'MyView');
// now fetch the data from the view
$coll = $view->execute();
</code>
++ Introduction
++ Levels of configuration
++ General attributes
+++ Portability
Each database management system (DBMS) has it's own behaviors. For example, some databases capitalize field names in their output, some lowercase them, while others leave them alone. These quirks make it difficult to port your scripts over to another server type. Doctrine strives to overcome these differences so your program can switch between DBMS's without any changes.
You control which portability modes are enabled by using the portability configuration option. Configuration options are set via {{factory()}} and {{setOption()}}.
The portability modes are bitwised, so they can be combined using {{|}} and removed using {{^}}. See the examples section below on how to do this.
++++ Portability Mode Constants
: {{Doctrine::PORTABILITY_ALL}} (default) : turn on all portability features. this is the default setting.
: {{Doctrine::PORTABILITY_DELETE_COUNT}} : Force reporting the number of rows deleted. Some DBMS's don't count the number of rows deleted when performing simple {{DELETE FROM}} tablename queries. This mode tricks such DBMS's into telling the count by adding {{WHERE 1=1}} to the end of {{DELETE}} queries.
: {{Doctrine::PORTABILITY_EMPTY_TO_NULL}} : Convert empty strings values to null in data in and output. Needed because Oracle considers empty strings to be null, while most other DBMS's know the difference between empty and null.
: {{Doctrine::PORTABILITY_ERRORS}} : Makes certain error messages in certain drivers compatible with those from other DBMS's
: {{Doctrine::PORTABILITY_FIX_ASSOC_FIELD_NAMES}} : This removes any qualifiers from keys in associative fetches. some RDBMS , like for example SQLite, will be default use the fully qualified name for a column in assoc fetches if it is qualified in a query.
: {{Doctrine::PORTABILITY_FIX_CASE}} : Convert names of tables and fields to lower or upper case in all methods. The case depends on the {{field_case}} option that may be set to either {{CASE_LOWER}} (default) or {{CASE_UPPER}}
: {{Doctrine::PORTABILITY_NONE}} : Turn off all portability features
: {{Doctrine::PORTABILITY_NUMROWS}} : Enable hack that makes {{numRows()}} work in Oracle
: {{Doctrine::PORTABILITY_EXPR}} : Makes DQL API throw exceptions when non-portable expressions are being used.
: {{Doctrine::PORTABILITY_RTRIM}} : Right trim the data output for all data fetches. This does not applied in drivers for RDBMS that automatically right trim values of fixed length character values, even if they do not right trim value of variable length character values.
++++ Examples
Using {{setAttribute()}} to enable portability for lowercasing and trimming
<code type="php">
$conn->setAttribute('portability',
Doctrine::PORTABILITY_FIX_CASE | Doctrine::PORTABILITY_RTRIM);
</code>
Using {{setAttribute()}} to enable all portability options except trimming
<code type="php">
$conn->setAttribute('portability',
Doctrine::PORTABILITY_ALL ^ Doctrine::PORTABILITY_RTRIM);
</code>
+++ Identifier quoting
You can quote the db identifiers (table and field names) with {{quoteIdentifier()}}. The delimiting style depends on which database driver is being used.
NOTE: just because you CAN use delimited identifiers, it doesn't mean you SHOULD use them. In general, they end up causing way more problems than they solve. Anyway, it may be necessary when you have a reserved word as a field name (in this case, we suggest you to change it, if you can).
Some of the internal Doctrine methods generate queries. Enabling the {{quote_identifier}} attribute of Doctrine you can tell Doctrine to quote the identifiers in these generated queries. For all user supplied queries this option is irrelevant.
Portability is broken by using the following characters inside delimited identifiers:
* backtick (`) -- due to MySQL
* double quote (") -- due to Oracle
* brackets ([ or ]) -- due to Access
Delimited identifiers are known to generally work correctly under the following drivers:
* Mssql
* Mysql
* Oracle
* Pgsql
* Sqlite
* Firebird
When using the {{ATTR_QUOTE_IDENTIFIER}} option, all of the field identifiers will be automatically quoted in the resulting SQL statements:
<code type="php">
$conn->setAttribute(Doctrine::ATTR_QUOTE_IDENTIFIER, true);
</code>
will result in a SQL statement that all the field names are quoted with the backtick '`' operator (in MySQL).
<code type="sql">
SELECT * FROM `sometable` WHERE `id` = '123'
</code>
as opposed to:
<code type="sql">
SELECT * FROM sometable WHERE id='123'
</code>
+++ Exporting
The export attribute is used for telling Doctrine what it should export when exporting classes.
If you don't want to export anything when calling export() you can use:
<code type="php">
$manager->setAttribute(Doctrine::ATTR_EXPORT, Doctrine::EXPORT_NONE);
</code>
For exporting tables only (but not constraints) you can use on of the following:
<code type="php">
$manager->setAttribute(Doctrine::ATTR_EXPORT, Doctrine::EXPORT_TABLES);
// or you can use
$manager->setAttribute(Doctrine::ATTR_EXPORT, Doctrine::EXPORT_ALL ^ Doctrine::EXPORT_CONSTRAINTS);
</code>
For exporting everything (tables and constraints) you can use:
<code type="php">
$manager->setAttribute(Doctrine::ATTR_EXPORT, Doctrine::EXPORT_ALL);
</code>
+++ Event listener
<code type="php">
// setting default event listener
$manager->setAttribute(Doctrine::ATTR_LISTENER, new MyListener());
</code>
++ Naming convention attributes
Naming convention attributes affect on the naming of different database related elements such as tables, indexes and sequences. Basically every naming convention attribute has affect in both ways. When importing schemas from the database to classes and when exporting classes into database.
So for example by default Doctrine naming convention for indexes is %s_idx. Not only do the indexes you set get a special suffix, also the imported classes get their indexes mapped to their non-suffixed equivalents. This applies to all naming convention attributes.
+++ Index name format
Doctrine::ATTR_IDXNAME_FORMAT can be used for changing the naming convention of indexes. By default Doctrine uses the format [name]_idx. So defining an index called 'ageindex' will actually be converted into 'ageindex_idx'.
<code type="php">
// changing the index naming convention
$manager->setAttribute(Doctrine::ATTR_IDXNAME_FORMAT, '%s_index');
</code>
+++ Sequence name format
Similar to Doctrine::ATTR_IDXNAME_FORMAT, Doctrine::ATTR_SEQNAME_FORMAT can be used for changing the naming convention of sequences. By default Doctrine uses the format [name]_seq, hence creating a new sequence with the name of 'mysequence' will lead into creation of sequence called 'mysequence_seq'.
<code type="php">
// changing the sequence naming convention
$manager->setAttribute(Doctrine::ATTR_IDXNAME_FORMAT, '%s_sequence');
</code>
+++ Table name format
+++ Database name format
<code type="php">
// changing the database naming convention
$manager->setAttribute(Doctrine::ATTR_DBNAME_FORMAT, 'myframework_%s');
</code>
++ Validation attributes
Doctrine provides complete control over what it validates. The validation procedure can be controlled with Doctrine::ATTR_VALIDATE.
The validation modes are bitwised, so they can be combined using {{|}} and removed using {{^}}. See the examples section below on how to do this.
+++ Validation mode constants
: {Doctrine::VALIDATE_NONE} : Turns off the whole validation procedure. This is the default value.
: {Doctrine::VALIDATE_LENGTHS} : Makes Doctrine validate all field lengths.
: {Doctrine::VALIDATE_TYPES} : Makes Doctrine validate all field types. Doctrine does loose type validation. This means that for example string with value '13.3' will not pass as an integer but '13' will.
: {Doctrine::VALIDATE_CONSTRAINTS} : Makes Doctrine validate all field constraints such as notnull, email etc.
: {Doctrine::VALIDATE_ALL} : Turns on all validations.
+++ Examples
Turning on all validations:
<code type="php">
$manager->setAttribute(Doctrine::ATTR_VALIDATE, Doctrine::VALIDATE_ALL);
</code>
Validating lengths and types, but not constraints:
<code type="php">
$manager->setAttribute(Doctrine::ATTR_VALIDATE, Doctrine::VALIDATE_LENGTHS | Doctrine::VALIDATE_TYPES);
</code>
<code type="php">
$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(Doctrine::ATTR_LISTENER, new MyListener());
</code>
Doctrine has a three-level configuration structure. You can set configuration attributes in global, connection and table level. If the same attribute is set on both lower level and upper level, the uppermost attribute will always be used. So for example if user first sets default fetchmode in global level to {{Doctrine::FETCH_BATCH}} and then sets {{example}} table fetchmode to {{Doctrine::FETCH_LAZY}}, the lazy fetching strategy will be used whenever the records of 'example' table are being fetched.
: **Global level** : The attributes set in global level will affect every connection and every table in each connection.
: **Connection level** : The attributes set in connection level will take effect on each table in that connection.
: **Table level** : The attributes set in table level will take effect only on that table.
In the following example we set an attribute at the global level:
<code type="php">
// setting a global level attribute
$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(Doctrine::ATTR_VALIDATE, Doctrine::VALIDATE_ALL);
</code>
In the next example above we override the global attribute on given connection.
<code type="php">
// setting a connection level attribute
// (overrides the global level attribute on this connection)
$conn = $manager->openConnection(new PDO('dsn', 'username', 'pw'));
$conn->setAttribute(Doctrine::ATTR_VALIDATE, Doctrine::VALIDATE_NONE);
</code>
In the last example we override once again the connection level attribute in the table level.
<code type="php">
// setting a table level attribute
// (overrides the connection/global level attribute on this table)
$table = $conn->getTable('User');
$table->setAttribute(Doctrine::ATTR_LISTENER, new UserListener());
</code>
++ DSN, the Data Source Name
++ Opening a new connection
++ Lazy-connecting to database
++ Managing connections
++ Connection-component binding
Doctrine allows you to bind connections to components (= your ActiveRecord classes). This means everytime a component issues a query or data is being fetched from the table the component is pointing at Doctrine will use the bound connection.
<code type="php">
$conn = $manager->openConnection(new PDO('dsn','username','password'), 'connection 1');
$conn2 = $manager->openConnection(new PDO('dsn2','username2','password2'), 'connection 2');
$manager->bindComponent('User', 'connection 1');
$manager->bindComponent('Group', 'connection 2');
$q = new Doctrine_Query();
// Doctrine uses 'connection 1' for fetching here
$users = $q->from('User u')->where('u.id IN (1,2,3)')->execute();
// Doctrine uses 'connection 2' for fetching here
$groups = $q->from('Group g')->where('g.id IN (1,2,3)')->execute();
</code>
In order to connect to a database through Doctrine, you have to create a valid DSN - data source name.
Doctrine supports both PEAR DB/MDB2 like data source names as well as PDO style data source names. The following section deals with PEAR like data source names. If you need more info about the PDO-style data source names see [[php PDO->__construct()]].
The DSN consists in the following parts:
||~ DSN part ||~ Description ||
|| phptype || Database backend used in PHP (i.e. mysql , pgsql etc.) ||
|| dbsyntax || Database used with regards to SQL syntax etc. ||
|| protocol || Communication protocol to use ( i.e. tcp, unix etc.) ||
|| hostspec || Host specification (hostname[:port]) ||
|| database || Database to use on the DBMS server ||
|| username || User name for login ||
|| password || Password for login ||
|| proto_opts || Maybe used with protocol ||
|| option || Additional connection options in URI query string format. Options are separated by ampersand (&). The Following table shows a non complete list of options: ||
**List of options**
||~ Name ||~ Description ||
|| charset || Some backends support setting the client charset.||
|| new_link || Some RDBMS do not create new connections when connecting to the same host multiple times. This option will attempt to force a new connection. ||
The DSN can either be provided as an associative array or as a string. The string format of the supplied DSN is in its fullest form:
<code>phptype(dbsyntax)://username:password@protocol+hostspec/database?option=value</code>
Most variations are allowed:
<code>
phptype://username:password@protocol+hostspec:110//usr/db_file.db
phptype://username:password@hostspec/database
phptype://username:password@hostspec
phptype://username@hostspec
phptype://hostspec/database
phptype://hostspec
phptype:///database
phptype:///database?option=value&anotheroption=anothervalue
phptype(dbsyntax)
phptype
</code>
The currently supported database backends are:
||~ Driver name ||~ Supported databases ||
|| firbird || Firebird ||
|| informix || Informix ||
|| mssql || Microsoft SQL Server ||
|| mysql || MySQL ||
|| oracle || Oracle ||
|| pgsql || PostgreSQL ||
|| sqlite || SQLite ||
A second DSN format supported is
<code>
phptype(syntax)://user:pass@protocol(proto_opts)/database
</code>
If your database, option values, username or password contain characters used to delineate DSN parts, you can escape them via URI hex encodings:
||~ Character ||~ Hex Code ||
|| : || %3a ||
|| / || %2f ||
|| @ || %40 ||
|| + || %2b ||
|| ( || %28 ||
|| ) || %29 ||
|| ? || %3f ||
|| = || %3d ||
|| & || %26 ||
Warning
Please note, that some features may be not supported by all database backends.
+++ Examples
**Example 1.** Connect to database through a socket
<code>
mysql://user@unix(/path/to/socket)/pear
</code>
**Example 2.** Connect to database on a non standard port
<code>
pgsql://user:pass@tcp(localhost:5555)/pear
</code>
**Example 3.** Connect to SQLite on a Unix machine using options
<code>
sqlite:////full/unix/path/to/file.db?mode=0666
</code>
**Example 4.** Connect to SQLite on a Windows machine using options
<code>
sqlite:///c:/full/windows/path/to/file.db?mode=0666
</code>
Lazy-connecting to database can save a lot of resources. There might be many pages where you don't need an actual database connection, hence its always recommended to use lazy-connecting (that means Doctrine will only connect to database when needed).
This feature can be very useful when using for example page caching, hence not actually needing a database connection on every request. Remember connecting to database is an expensive operation.
<code type="php">
$dsn = 'mysql://username:password@localhost/test';
// initalize a new Doctrine_Connection
$conn = Doctrine_Manager::connection($dsn);
// !! no actual database connection yet !!
// connects database and performs a query
$conn->query('FROM User u');
</code>
From the start Doctrine has been designed to work with multiple connections. Unless separately specified Doctrine always uses the current connection for executing the queries. The following example uses {{openConnection()}} second argument as an optional connection alias.
<code type="php">
// Doctrine_Manager controls all the connections
$manager = Doctrine_Manager::getInstance();
// open first connection
$conn = $manager->openConnection(new PDO('dsn','username','password'), 'connection 1');
</code>
For convenience {{Doctrine_Manager}} provides static method {{connection()}} which opens new connection when arguments are given to it and returns the current connection when no arguments have been speficied.
<code type="php">
// open first connection
$conn = Doctrine_Manager::connection(new PDO('dsn','username','password'), 'connection 1');
$conn2 = Doctrine_Manager::connection();
// $conn2 == $conn
</code>
The current connection is the lastly opened connection.
<code type="php">
// open second connection
$conn2 = $manager->openConnection(new PDO('dsn2','username2','password2'), 'connection 2');
$manager->getCurrentConnection(); // $conn2
</code>
You can change the current connection by calling {{setCurrentConnection()}}.
<code type="php">
$manager->setCurrentConnection('connection 1');
$manager->getCurrentConnection(); // $conn
</code>
You can iterate over the opened connection by simple passing the manager object to foreach clause. This is possible since {{Doctrine_Manager}} implements special {{IteratorAggregate}} interface.
<code type="php">
// iterating through connections
foreach($manager as $conn) {
}
</code>
Opening a new database connection in Doctrine is very easy. If you wish to use PDO (www.php.net/PDO) you can just initalize a new PDO object:
<code type="php">
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
</code>
Doctrine Data uses the Doctrine Parser for the dumping and loading of fixtures data so it is possible to use any of the formats available in the Parser. Currently yml is the only fully supported format but xml and others are next.
++ Exporting
You can export data to fixtures file in many different formats
<code type="php">
// A few ways exist for specifying where you export the data
// Dump to one large fixture file
$data = new Doctrine_Data();
$data->exportData('data.yml', 'yml');
// Dump to individual files. One file per model. 3rd argument true specifies to dump to individual files
$data = new Doctrine_Data();
$data->exportData('path/to/directory', 'yml', true);
</code>
++ Importing
You can import data from fixtures files in many different formats
<code type="php">
// Path can be in a few different formats
$path = 'path/to/data.yml'; // Path directly to one yml file
$path = array('data.yml', 'data2.yml', 'more.yml'); // Array of yml file paths
$path = array('directory1', 'directory2', 'directory3'); // Array of directories which contain yml files. It will find all files with an extension of .yml
// Specify the format of the data you are importing
$format = 'yml'; // xml, yml, json
$models = array('User', 'Phonenumber'); // you can optionally specify an array of the models you wish to import the data for, by default it loads data for all the available loaded models and the data that exists
$data = new Doctrine_Data();
$data->importData($path, $format, $models);
</code>
++ Dummy Data
With Doctrine Data you can import dummy data to all your Doctrine Records
<code type="php">
$numRecords = 3; // Number of dummy records to populate for each model
$models = array('User', 'Email'); // Models to generate dummy data for. If none specified it generates dummy data for all loaded models.
$data = new Doctrine_Data();
$data->importDummyData($numRecords, $models);
</code>
++ Writing
You can write your fixtures files manually and load them in to your applications. Below is a sample data.yml fixtures file. You can also split your data fixtures file up in to multiple files. Doctrine will read all fixtures files and parse them, then load all data.
Imagine a schema with the following relationships:
<code type="php">
Resource hasMany Tag as Tags
Resource hasOne ResourceType as Type
ResourceType hasMany Resource as Resources
Tag hasMany Resource as Resources
</code>
<code type="yml">
---
Resource:
Resource_1:
name: Doctrine Video Tutorial
Type: Video
Tags: [tutorial, doctrine, help]
Resource_2:
name: Doctrine Cheat Sheet
Type: Image
Tags: [tutorial, cheat, help]
ResourceType:
Video:
name: Video
Image:
name: Image
Tag:
tutorial:
name: tutorial
doctrine:
name: doctrine
help:
name: help
cheat:
name: cheat
</code>
You could optionally specify the Resources each tag is related to instead of specifying the Tags a Resource has.
<code type="yml">
Tag:
tutorial:
name: tutorial
Resources: [Resource_1, Resource_2]
doctrine:
name: doctrine
Resources: [Resource_1]
help:
name: help
Resources: [Resource_1, Resource_2]
cheat:
name: cheat
Resources: [Resource_1]
</code>
Here is how you would write code to load the data from that data.yml file
<code type="php">
$data = new Doctrine_Data();
$data->importData('data.yml', 'yml');
</code>
++ Fixtures For Nested Sets
Writing a fixtures file for a nested set tree is slightly different from writing regular fixtures files. The structure of the tree is defined like this:
<code type="yml">
---
Category:
Category_1:
title: Categories # the root node
children:
Category_2:
title: Category 1
Category_3:
title: Category 2
children:
Category_4:
title: Subcategory of Category 2
</code>
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
<code type="sql">
DELETE FROM <component_name>
[WHERE <where_condition>]
[ORDER BY ...]
[LIMIT <record_count>]
</code>
* The {{DELETE}} statement deletes records from {{component_name}} and returns the number of records deleted.
* The optional {{WHERE}} clause specifies the conditions that identify which records to delete. Without {{WHERE}} clause, all records are deleted.
* If the {{ORDER BY}} clause is specified, the records are deleted in the order that is specified.
* The {{LIMIT}} clause places a limit on the number of rows that can be deleted. The statement will stop as soon as it has deleted {{record_count}} records.
<code type="php">
$q = 'DELETE FROM Account WHERE id > ?';
$rows = $this->conn->query($q, array(3));
// the same query using the query interface
$q = new Doctrine_Query();
$rows = $q->delete('Account')
->from('Account a')
->where('a.id > ?', 3)
->execute();
print $rows; // the number of affected rows
</code>
+++ Introduction
+++ Comparisons using subqueries
+++ Conditional expressions
++++ ANY, IN and SOME
++++ ALL
++++ EXISTS and NOT EXISTS
+++ Correlated subqueries
+++ Subqueries in FROM clause
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment