Commit 876973a8 authored by hansbrix's avatar hansbrix

html->wiki conversion script

parent c4ca5964
Caching is one of the most influental things when it comes to performance tuning. Doctrine_Cache provides means for
caching queries and for managing the cached queries.
Caching is one of the most influental things when it comes to performance tuning. Doctrine_Cache provides means for
caching queries and for managing the cached queries.
<?php ?>
Doctrine_Db_Profiler is an eventlistener for Doctrine_Db. 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.
<br \><br \>
Doctrine_Db_Profiler can be enabled by adding it as an eventlistener for Doctrine_Db.
<br \><br \>
<?php
renderCode("<?php
?>");
?>
<?php ?>
Doctrine_Db_Profiler is an eventlistener for Doctrine_Db. 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_Db_Profiler can be enabled by adding it as an eventlistener for Doctrine_Db.
<code type="php">
?></code>
<code type="php">
class User {
public function setTableDefinition() {
$this->hasColumn("name", "string", 200);
$this->hasColumn("password", "string", 32);
}
public function setPassword($password) {
return md5($password);
}
public function getName($name) {
return strtoupper($name);
}
}
$user = new User();
$user->name = 'someone';
print $user->name; // someone
$user->password = '123';
print $user->password; // 123
$user->setAttribute(Doctrine::ATTR_LISTENER, new Doctrine_EventListener_AccessorInvoker());
print $user->name; // SOMEONE
$user->password = '123';
print $user->password; // 202cb962ac59075b964b07152d234b70
</code>
<code type="php">
class User {
public function setTableDefinition() {
$this->hasColumn("name", "string", 200);
$this->hasColumn("password", "string", 32);
}
public function setPassword($password) {
return md5($password);
}
public function getName($name) {
return strtoupper($name);
}
}
$user = new User();
$user->name = 'someone';
print $user->name; // someone
$user->password = '123';
print $user->password; // 123
$user->setAttribute(Doctrine::ATTR_LISTENER, new Doctrine_EventListener_AccessorInvoker());
print $user->name; // SOMEONE
$user->password = '123';
print $user->password; // 202cb962ac59075b964b07152d234b70
</code>
Creating a new listener is very easy. You can set the listener in global, connection or factory level.
<code type="php">
class MyListener extends Doctrine_EventListener {
public function onLoad(Doctrine_Record $record) {
print $record->getTable()->getComponentName()." just got loaded!";
}
public function onSave(Doctrine_Record $record) {
print "saved data access object!";
}
}
class MyListener2 extends Doctrine_EventListener {
public function onPreUpdate() {
try {
$record->set("updated",time());
} catch(InvalidKeyException $e) {
}
}
}
// setting global listener
$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(Doctrine::ATTR_LISTENER,new MyListener());
// setting connection level listener
$conn = $manager->openConnection($dbh);
$conn->setAttribute(Doctrine::ATTR_LISTENER,new MyListener2());
// setting factory level listener
$table = $conn->getTable("User");
$table->setAttribute(Doctrine::ATTR_LISTENER,new MyListener());
</code>
Creating a new listener is very easy. You can set the listener in global, connection or factory level.
<code type="php">
class MyListener extends Doctrine_EventListener {
public function onLoad(Doctrine_Record $record) {
print $record->getTable()->getComponentName()." just got loaded!";
}
public function onSave(Doctrine_Record $record) {
print "saved data access object!";
}
}
class MyListener2 extends Doctrine_EventListener {
public function onPreUpdate() {
try {
$record->set("updated",time());
} catch(InvalidKeyException $e) {
}
}
}
// setting global listener
$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(Doctrine::ATTR_LISTENER,new MyListener());
// setting connection level listener
$conn = $manager->openConnection($dbh);
$conn->setAttribute(Doctrine::ATTR_LISTENER,new MyListener2());
// setting factory level listener
$table = $conn->getTable("User");
$table->setAttribute(Doctrine::ATTR_LISTENER,new MyListener());
</code>
Here is a list of availible events and their parameters:
<code type="php">
interface Doctrine_EventListener_Interface {
public function onLoad(Doctrine_Record $record);
public function onPreLoad(Doctrine_Record $record);
public function onUpdate(Doctrine_Record $record);
public function onPreUpdate(Doctrine_Record $record);
public function onCreate(Doctrine_Record $record);
public function onPreCreate(Doctrine_Record $record);
public function onSave(Doctrine_Record $record);
public function onPreSave(Doctrine_Record $record);
public function onInsert(Doctrine_Record $record);
public function onPreInsert(Doctrine_Record $record);
public function onDelete(Doctrine_Record $record);
public function onPreDelete(Doctrine_Record $record);
public function onEvict(Doctrine_Record $record);
public function onPreEvict(Doctrine_Record $record);
public function onSleep(Doctrine_Record $record);
public function onWakeUp(Doctrine_Record $record);
public function onClose(Doctrine_Connection $connection);
public function onPreClose(Doctrine_Connection $connection);
public function onOpen(Doctrine_Connection $connection);
public function onTransactionCommit(Doctrine_Connection $connection);
public function onPreTransactionCommit(Doctrine_Connection $connection);
public function onTransactionRollback(Doctrine_Connection $connection);
public function onPreTransactionRollback(Doctrine_Connection $connection);
public function onTransactionBegin(Doctrine_Connection $connection);
public function onPreTransactionBegin(Doctrine_Connection $connection);
public function onCollectionDelete(Doctrine_Collection $collection);
public function onPreCollectionDelete(Doctrine_Collection $collection);
}
Here is a list of availible events and their parameters:
<code type="php">
interface Doctrine_EventListener_Interface {
public function onLoad(Doctrine_Record $record);
public function onPreLoad(Doctrine_Record $record);
public function onUpdate(Doctrine_Record $record);
public function onPreUpdate(Doctrine_Record $record);
public function onCreate(Doctrine_Record $record);
public function onPreCreate(Doctrine_Record $record);
public function onSave(Doctrine_Record $record);
public function onPreSave(Doctrine_Record $record);
public function onInsert(Doctrine_Record $record);
public function onPreInsert(Doctrine_Record $record);
public function onDelete(Doctrine_Record $record);
public function onPreDelete(Doctrine_Record $record);
public function onEvict(Doctrine_Record $record);
public function onPreEvict(Doctrine_Record $record);
public function onSleep(Doctrine_Record $record);
public function onWakeUp(Doctrine_Record $record);
public function onClose(Doctrine_Connection $connection);
public function onPreClose(Doctrine_Connection $connection);
public function onOpen(Doctrine_Connection $connection);
public function onTransactionCommit(Doctrine_Connection $connection);
public function onPreTransactionCommit(Doctrine_Connection $connection);
public function onTransactionRollback(Doctrine_Connection $connection);
public function onPreTransactionRollback(Doctrine_Connection $connection);
public function onTransactionBegin(Doctrine_Connection $connection);
public function onPreTransactionBegin(Doctrine_Connection $connection);
public function onCollectionDelete(Doctrine_Collection $collection);
public function onPreCollectionDelete(Doctrine_Collection $collection);
}
<code type="php">
$table = $conn->getTable("User");
$table->setEventListener(new MyListener2());
// retrieve user whose primary key is 2
$user = $table->find(2);
$user->name = "John Locke";
// update event will be listened and current time will be assigned to the field 'updated'
$user->save();
</code>
<code type="php">
$table = $conn->getTable("User");
$table->setEventListener(new MyListener2());
// retrieve user whose primary key is 2
$user = $table->find(2);
$user->name = "John Locke";
// update event will be listened and current time will be assigned to the field 'updated'
$user->save();
</code>
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.
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.
<code type="php">
$hook = new Doctrine_Hook($table, $fields);
</code>
<code type="php">
$hook = new Doctrine_Hook($table, $fields);
</code>
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>
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>
[<b>Note</b>: The term 'Transaction' doesnt refer to database transactions here but to the general meaning of this term]<br />
[<b>Note</b>: This component is in <b>Alpha State</b>]<br />
<br />
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.<br />
<br />
<b>Optimistic Locking:</b><br />
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.<br />
<br />
<b>Pessimistic Locking:</b><br />
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.<br />
<br />
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.
[**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.
Roman Borschel - romanb at #doctrine (freenode)<br />
Roman Borschel - romanb at #doctrine (freenode)
Don't hesitate to contact me if you have questions, ideas, ect.
- Possibility to release locks of a specific Record type (i.e. releasing all locks on 'User'
- Possibility to release locks of a specific Record type (i.e. releasing all locks on 'User'
objects).
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.
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.
......@@ -3,21 +3,27 @@ You can think of this validation as a gateway that needs to be passed right befo
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).<br />
<br />
Once you enabled validation, you'll get a bunch of validations automatically:<br />
<br />
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).<br /><br />
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_VLD, true);
</code>
<code type="php">
// turning on validation
Doctrine_Manager::getInstance()->setAttribute(Doctrine::ATTR_VLD, true);
</code>
Here is a list of predefined validators. You cannot use these names for your custom validators.
|| **name** || **arguments** || **task** ||
|| email || || Check if value is valid email.||
|| notblank || || Check if value is not blank.||
|| notnull || || Check if value is not null.||
|| country || || Check if valid is valid country code.||
|| ip || || Checks if value is valid IP (internet protocol) address.||
|| htmlcolor || || Checks if value is valid html color.||
|| nospace || || Check if value has no space chars. ||
|| range || [min,max] || Checks if value is in range specified by arguments.||
|| unique || || Checks if value is unique in its database table. ||
|| regexp || [expression] || Check if valie matches a given regexp. ||
Here is a list of predefined validators. You cannot use these names for your custom validators.
|| **name** || **arguments** || **task** ||
|| email || || Check if value is valid email.||
|| notblank || || Check if value is not blank.||
|| notnull || || Check if value is not null.||
|| country || || Check if valid is valid country code.||
|| ip || || Checks if value is valid IP (internet protocol) address.||
|| htmlcolor || || Checks if value is valid html color.||
|| nospace || || Check if value has no space chars. ||
|| range || [min,max] || Checks if value is in range specified by arguments.||
|| unique || || Checks if value is unique in its database table. ||
|| regexp || [expression] || Check if valie matches a given regexp. ||
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.<br />
<br />
Doctrine provides some mechanisms that can be used to validate your data in more detail.
Validators: 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:<br />
<br />
- You can write the validator on your own.<br />
- You can propose your need for a new validator to a Doctrine developer.<br />
- You can use validation hooks.<br />
<br />
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:<br />
<br />
- validate() (Executed every time the record gets validated)<br />
- validateOnInsert() (Executed when the record is new and gets validated)<br />
- validateOnUpdate() (Executed when the record is not new and gets validated)<br />
<br />
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:<br />
validation:
<code type="php">
class User extends Doctrine_Record {
......
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.<br />
<br />
Implicit validation:<br />
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
......@@ -10,15 +13,20 @@ an ordinary array with references to all records that did not pass validation. Y
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.<br />
<br />
Explicit validation:<br />
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().<br />
<br />
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">
......
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.
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.
<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>
<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>
<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>
<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>
There are couple of availible Cache attributes on Doctrine:
<ul>
<li \>Doctrine::ATTR_CACHE_SIZE
<ul>
<li \> Defines which cache container Doctrine uses
<li \> Possible values: Doctrine::CACHE_* (for example Doctrine::CACHE_FILE)
</ul>
<li \>Doctrine::ATTR_CACHE_DIR
<ul>
<li \> cache directory where .cache files are saved
<li \> the default cache dir is %ROOT%/cachedir, where
%ROOT% is automatically converted to doctrine root dir
</ul>
<li \>Doctrine::ATTR_CACHE_SLAM
<ul>
<li \> 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
</ul>
<li \>Doctrine::ATTR_CACHE_SIZE
<ul>
<li \> Cache size attribute
</ul>
<li \>Doctrine::ATTR_CACHE_TTL
<ul>
<li \> How often the cache is cleaned
</ul>
</ul>
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 has very comprehensive and fast caching solution.
Its cache is <b>always up-to-date</b>.
In order to achieve this doctrine does the following things:
<br /><br />
<table border=1 class='dashed' cellpadding=0 cellspacing=0>
<tr><td>
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.
<br /><br />
2. When retrieving records from the database doctrine always tries to hit the cache first.
<br /><br />
3. If a record (Doctrine_Record) is retrieved from database or inserted into database it will be saved into cache.
<br /><br />
4. When a Data Access Object is deleted or updated it will be deleted from the cache
</td></tr>
</table>
<br /><br />
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:
<br /><br />
<table border=1 class='dashed' cellpadding=0 cellspacing=0>
<tr><td>
1. Every time a cache file is accessed the id of that record will be added into the $fetched property of Doctrine_Cache
<br /><br />
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
<br /><br />
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.
<br /><br />
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.
</td></tr>
</table>
<br /><br />
So for every 199 fast page loads there is one page load which suffers a little overhead from the cache cleaning operation.
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.
Doctrine_Cache offers many options for performance fine-tuning:
<ul>
<li \> savePropability <br \>
Option that defines the propability of which
a query is getting cached.
<br \><br \>
<li \> cleanPropability <br \>
Option that defines the propability the actual cleaning will occur
when calling Doctrine_Cache::clean();
<br \><br \>
<li \> statsPropability
<ul \>
Doctrine_Cache offers many options for performance fine-tuning:
* savePropability
Option that defines the propability of which
a query is getting cached.
* cleanPropability
Option that defines the propability the actual cleaning will occur
when calling Doctrine_Cache::clean();
* statsPropability
<ul \>
<?php ?>
Doctrine_Cache offers an intuitive and easy-to-use query caching solution. It provides the following things:
<ul>
<li \> Multiple cache backends to choose from (including Memcached, APC and Sqlite)
<br \><br \>
<li \> 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.
<br \><br \>
<li \> Advanced options for fine-tuning. Doctrine_Cache has many options for fine-tuning performance.
<br \><br \>
<li \> Cache hooks itself directly into Doctrine_Db eventlistener system allowing it to be easily added on-demand.
</ul>
<br \><br \>
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.
<br \><br \>
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.
<br \><br \>
<br \><br \>
Initializing a new cache instance:
<br \><br \>
<?php
renderCode("<?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);
?>");
?>
<br \><br \>
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.
<br \><br \>
<?php ?>
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.
<ul>
<li \>Negative numbers are not permitted as indices.
</ul>
<ul>
<li \>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.
</ul>
<ul>
<li \>When declaring indexed arrays with the array construct, a trailing space must be added after each comma delimiter to improve readability.
</ul>
<ul>
<li \>It is also permitted to declare multiline indexed arrays using the "array" construct. In this case, each successive line must be padded with spaces.
</ul>
<ul>
<li \>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:
</ul>
<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');
* 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');
<ul>
<li \>Classes must be named by following the naming conventions.
</ul>
<ul>
<li \>The brace is always written right after the class name (or interface declaration).
</ul>
<ul>
<li \>Every class must have a documentation block that conforms to the PHPDocumentor standard.
</ul>
<ul>
<li \>Any code within a class must be indented four spaces.
</ul>
<ul>
<li \>Only one class is permitted per PHP file.
</ul>
<ul>
<li \>Placing additional code in a class file is NOT permitted.
</ul>
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
}
* Classes must be named by following the naming conventions.
* The brace is always written right 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
}
<?php ?>
<ul>
<li \>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.
</ul>
<ul>
<li \>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.
</ul>
<ul>
<li \>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.
</ul>
<?php
renderCode("<?php
if (\$foo != 2) {
\$foo = 2;
}");
?>
<ul>
<li \>For "if" statements that include "elseif" or "else", the formatting must be as in these examples:
</ul>
<?php
renderCode("<?php
if (\$foo != 1) {
\$foo = 1;
} else {
\$foo = 3;
}
if (\$foo != 2) {
\$foo = 2;
} elseif (\$foo == 1) {
\$foo = 3;
} else {
\$foo = 11;
}");
?>
<ul>
<li \>PHP allows for these statements to be written without braces in some circumstances, the following format for if statements is also allowed:
</ul>
<?php
renderCode("<?php
if (\$foo != 1)
\$foo = 1;
else
\$foo = 3;
if (\$foo != 2)
\$foo = 2;
elseif (\$foo == 1)
\$foo = 3;
else
\$foo = 11;
");
?>
<ul>
<li \>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.
</ul>
<ul>
<li \>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.
</ul>
<?php
renderCode("<?php
switch (\$case) {
case 1:
case 2:
break;
case 3:
break;
default:
break;
}
?>");
?>
<ul>
<li \>The construct default may never be omitted from a switch statement.
</ul>
<?php ?>
* 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>
* PHP allows for these statements to be written without braces in some circumstances, the following format for if statements is also allowed:
<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>
* 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.
<?php ?>
* 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 right 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 the function declarations section 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>
<?php ?>
* 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 right 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 the function declarations section 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>
Documentation Format
<ul>
<li \>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/
</ul>
Methods:
<ul>
<li \>Every method, must have a docblock that contains at a minimum:
</ul>
<ul>
<li \>A description of the function
</ul>
<ul>
<li \>All of the arguments
</ul>
<ul>
<li \>All of the possible return values
</ul>
<ul>
<li \>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.
</ul>
<ul>
<li \>If a function/method may throw an exception, use @throws:
</ul>
<ul>
<li \>@throws exceptionclass [description]
</ul>
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]
PHP code must always be delimited by the full-form, standard PHP tags (<?php ?>)
Short tags are never allowed. For files containing only PHP code, the closing tag must always be omitted
PHP code must always be delimited by the full-form, standard PHP tags (<?php ?>)
Short tags are never allowed. For files containing only PHP code, the closing tag must always be omitted
<ul>
<li \>When a string is literal (contains no variable substitutions), the apostrophe or "single quote" must always used to demarcate the string:
</ul>
<ul>
<li \>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:
</ul>
<ul>
<li \>Variable substitution is permitted using the following form:
</ul>
<ul>
<li \>Strings may be concatenated using the "." operator. A space must always be added before and after the "." operator to improve readability:
</ul>
<ul>
<li \>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:
</ul>
<code type="php">
// literal string
$string = 'something';
// string contains apostrophes
$sql = "SELECT id, name FROM people WHERE name = 'Fred' OR name = 'Susan'";
// variable substitution
$greeting = "Hello $name, welcome back!";
// concatenation
$framework = 'Doctrine' . ' ORM ' . 'Framework';
// concatenation line breaking
$sql = "SELECT id, name FROM user "
. "WHERE name = ? "
. "ORDER BY name ASC";
* When a string is literal (contains no variable substitutions), the apostrophe or "single quote" must always used to demarcate the string:
* 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:
* Variable substitution is permitted using the following form:
* Strings may be concatenated using the "." operator. A space must always be added before and after the "." operator to improve readability:
* 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">
// literal string
$string = 'something';
// string contains apostrophes
$sql = "SELECT id, name FROM people WHERE name = 'Fred' OR name = 'Susan'";
// variable substitution
$greeting = "Hello $name, welcome back!";
// concatenation
$framework = 'Doctrine' . ' ORM ' . 'Framework';
// concatenation line breaking
$sql = "SELECT id, name FROM user "
. "WHERE name = ? "
. "ORDER BY name ASC";
<ul>
<li \>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.
</ul>
<ul>
<li \>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".
</ul>
<ul>
<li \>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.
</ul>
* 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.
Following rules must apply to all constants used within Doctrine framework:
<ul><li \> Constants may contain both alphanumeric characters and the underscore.</ul>
<ul><li \> Constants must always have all letters capitalized.</ul>
<ul><li \> 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.
</ul>
<ul><li \> Constants must be defined as class members by using the "const" construct. Defining constants in the global scope with "define" is NOT permitted.
</ul>
Following rules must apply to all constants used within Doctrine framework:
<code type="php">
class Doctrine_SomeClass {
const MY_CONSTANT = 'something';
}
print Doctrine_SomeClass::MY_CONSTANT;
</code>
* 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>
<ul>
<li \>For all other files, only alphanumeric characters, underscores, and the dash character ("-") are permitted. Spaces are prohibited.
</ul>
<ul>
<li \>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:
<br \> <br \>
Doctrine/Db.php <br \>
<br \>
Doctrine/Connection/Transaction.php <br \>
</ul>
<ul>
<li \>File names must follow the mapping to class names described above.
</ul>
* 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.
<ul>
<li>Function names may only contain alphanumeric characters. Underscores are not permitted. Numbers are permitted in function names but are discouraged.
</ul>
<ul>
<li>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.
</ul>
<ul>
<li>Verbosity is encouraged. Function names should be as verbose as is practical to enhance the understandability of code.
</ul>
<ul>
<li>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.
</ul>
<ul>
<li>Functions in the global scope ("floating functions") are NOT permmitted. All static functions should be wrapped in a static class.
</ul>
<li>Function names may only contain alphanumeric characters. Underscores are not permitted. Numbers are permitted in function names but are discouraged.
<li>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.
<li>Verbosity is encouraged. Function names should be as verbose as is practical to enhance the understandability of code.
<li>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.
<li>Functions in the global scope ("floating functions") are NOT permmitted. All static functions should be wrapped in a static class.
<ul>
<li \>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:
<br \><br \>
Doctrine_Db_EventListener_Interface <br \>
<br \>
Doctrine_EventListener_Interface <br \>
</ul>
* 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
All variables must satisfy the following conditions:
<ul>
<li \>Variable names may only contain alphanumeric characters. Underscores are not permitted. Numbers are permitted in variable names but are discouraged.
</ul>
<ul>
<li \>Variable names must always start with a lowercase letter and follow the "camelCaps" capitalization convention.
</ul>
<ul>
<li \>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.
</ul>
<ul>
<li \>Within the framework certain generic object variables should always use the following names:
<ul>
<li \> Doctrine_Connection -> <i>$conn</i>
<li \> Doctrine_Collection -> <i>$coll</i>
<li \> Doctrine_Manager -> <i>$manager</i>
<li \> Doctrine_Query -> <i>$query</i>
<li \> Doctrine_Db -> <i>$db</i>
</ul>
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.
</ul>
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:
* 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.
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.
<br \><br \>
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.
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.
Use an indent of 4 spaces, with no tabs.
Use an indent of 4 spaces, with no tabs.
<ul>
<li \>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.
</ul>
<ul>
<li \>Do not use carriage returns (CR) like Macintosh computers (0x0D).
</ul>
<ul>
<li \>Do not use the carriage return/linefeed combination (CRLF) as Windows computers (0x0D, 0x0A).
</ul>
* 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).
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.
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.
<b>CLASSES</b><br \><br \>
<ul>
<li \>
All test classes should be referring to a class or specific testing aspect of some class.
<br \><br \>
For example <i>Doctrine_Record_TestCase</i> is a valid name since its referring to class named
<i>Doctrine_Record</i>.
<br \><br \>
<i>Doctrine_Record_State_TestCase</i> is also a valid name since its referring to testing the state aspect
of the Doctrine_Record class.
<br \><br \>
However something like <i>Doctrine_PrimaryKey_TestCase</i> is not valid since its way too generic.
<br \><br \>
<li \> Every class should have atleast one TestCase equivalent
<li \> All testcase classes should inherit Doctrine_UnitTestCase
</ul>
<br \><br \>
<b>METHODS</b><br \><br \>
<ul>
<li \>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.<br \><br \>
For example <i>Doctrine_Export_Pgsql_TestCase::testCreateTableSupportsAutoincPks()</i> 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.
<br \><br \>
NOTE: Commonly used testing method naming convention TestCase::test[methodName] is *NOT* allowed in Doctrine. So in this case
<b class='title'>Doctrine_Export_Pgsql_TestCase::testCreateTable()</b> would not be allowed!
<br \><br \>
<li \>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.
</ul>
<b>ASSERTIONS</b><br \><br \>
<ul>
<li \>There should never be assertions within any loops and rarely within functions.
**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
<b class='title'>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.
<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">
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>
<code type="php">
// custom primary key column name
class Group extends Doctrine_Record {
public function setUp() {
$this->setPrimaryKeyColumn("group_id");
}
}
</code>
<code type="php">
$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(Doctrine::ATTR_LISTENER, new MyListener());
</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.
<br \><br \>
<li> Global level
<ul>
The attributes set in global level will affect every connection and every table in each connection.
</ul>
<li> Connection level
<ul>
The attributes set in connection level will take effect on each table in that connection.
</ul>
<li> Table level
<ul>
The attributes set in table level will take effect only on that table.
</ul>
<code type="php">
// setting a global level attribute
$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(Doctrine::ATTR_VLD, false);
// 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_VLD, true);
// 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>
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.
<li> Global level
The attributes set in global level will affect every connection and every table in each connection.
<li> Connection level
The attributes set in connection level will take effect on each table in that connection.
<li> Table level
The attributes set in table level will take effect only on that table.
<code type="php">
// setting a global level attribute
$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(Doctrine::ATTR_VLD, false);
// 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_VLD, true);
// 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>
<li> Doctrine::ATTR_LISTENER
<li> Doctrine::ATTR_FETCHMODE = 2;
<li> Doctrine::ATTR_CACHE_DIR = 3;
<li> Doctrine::ATTR_CACHE_TTL = 4;
<li> Doctrine::ATTR_CACHE_SIZE = 5;
<li> Doctrine::ATTR_CACHE_SLAM = 6;
<li> Doctrine::ATTR_CACHE = 7;
<li> Doctrine::ATTR_BATCH_SIZE = 8;
<li> Doctrine::ATTR_PK_COLUMNS = 9;
/**
* primary key type attribute
*/
<li> Doctrine::ATTR_PK_TYPE = 10;
/**
* locking attribute
*/
<li> Doctrine::ATTR_LOCKMODE = 11;
/**
* validatate attribute
*/
<li> Doctrine::ATTR_VLD = 12;
/**
* name prefix attribute
*/
<li> Doctrine::ATTR_NAME_PREFIX = 13;
/**
* create tables attribute
*/
<li> Doctrine::ATTR_CREATE_TABLES = 14;
/**
* collection key attribute
*/
<li> Doctrine::ATTR_COLL_KEY = 15;
/**
* collection limit attribute
*/
<li> Doctrine::ATTR_COLL_LIMIT = 16;
<li> Doctrine::ATTR_LISTENER
<li> Doctrine::ATTR_FETCHMODE = 2;
<li> Doctrine::ATTR_CACHE_DIR = 3;
<li> Doctrine::ATTR_CACHE_TTL = 4;
<li> Doctrine::ATTR_CACHE_SIZE = 5;
<li> Doctrine::ATTR_CACHE_SLAM = 6;
<li> Doctrine::ATTR_CACHE = 7;
<li> Doctrine::ATTR_BATCH_SIZE = 8;
<li> Doctrine::ATTR_PK_COLUMNS = 9;
/**
* primary key type attribute
*/
<li> Doctrine::ATTR_PK_TYPE = 10;
/**
* locking attribute
*/
<li> Doctrine::ATTR_LOCKMODE = 11;
/**
* validatate attribute
*/
<li> Doctrine::ATTR_VLD = 12;
/**
* name prefix attribute
*/
<li> Doctrine::ATTR_NAME_PREFIX = 13;
/**
* create tables attribute
*/
<li> Doctrine::ATTR_CREATE_TABLES = 14;
/**
* collection key attribute
*/
<li> Doctrine::ATTR_COLL_KEY = 15;
/**
* collection limit attribute
*/
<li> Doctrine::ATTR_COLL_LIMIT = 16;
<code type="php">
// setting default batch size for batch collections
$manager->setAttribute(Doctrine::ATTR_BATCH_SIZE, 7);
</code>
<code type="php">
// setting default batch size for batch collections
$manager->setAttribute(Doctrine::ATTR_BATCH_SIZE, 7);
</code>
<code type="php">
// setting default event listener
$manager->setAttribute(Doctrine::ATTR_LISTENER, new MyListener());
</code>
<code type="php">
// setting default event listener
$manager->setAttribute(Doctrine::ATTR_LISTENER, new MyListener());
</code>
<code type="php">
// sets the default collection type (fetching strategy)
$manager->setAttribute(Doctrine::ATTR_FETCHMODE, Doctrine::FETCH_LAZY);
</code>
<code type="php">
// sets the default collection type (fetching strategy)
$manager->setAttribute(Doctrine::ATTR_FETCHMODE, Doctrine::FETCH_LAZY);
</code>
<?php ?>
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:
<br \> <br \>
<ul>
<li \>backtick (`) -- due to MySQL
<li \>double quote (") -- due to Oracle
<li \>brackets ([ or ]) -- due to Access
</ul>
Delimited identifiers are known to generally work correctly under the following drivers:
<br \>
<ul>
<li \>Mssql
<li \>Mysql
<li \>Oracle
<li \>Pgsql
<li \>Sqlite
<li \>Firebird
</ul>
When using the quoteIdentifiers option, all of the field identifiers will be automatically quoted in the resulting SQL statements:
<br \><br \>
<?php
renderCode("<?php
\$conn->setAttribute('quote_identifiers', true);
?>");
?>
<br \><br \>
will result in a SQL statement that all the field names are quoted with the backtick '`' operator (in MySQL).
<br \>
<div class='sql'>SELECT * FROM `sometable` WHERE `id` = '123'</div>
<br \>
as opposed to:
<br \>
<div class='sql'>SELECT * FROM sometable WHERE id='123'</div>
<?php ?>
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 quoteIdentifiers option, all of the field identifiers will be automatically quoted in the resulting SQL statements:
<code type="php">
\$conn->setAttribute('quote_identifiers', true);
?></code>
will result in a SQL statement that all the field names are quoted with the backtick '`' operator (in MySQL).
<div class='sql'>SELECT * FROM `sometable` WHERE `id` = '123'</div>
as opposed to:
<div class='sql'>SELECT * FROM sometable WHERE id='123'</div>
<code type="php">
// sets the default offset collection limit
$manager->setAttribute(Doctrine::ATTR_COLL_LIMIT, 10);
</code>
<code type="php">
// sets the default offset collection limit
$manager->setAttribute(Doctrine::ATTR_COLL_LIMIT, 10);
</code>
<?php ?>
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. PEAR 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.
<br \><br \>
Portability Mode Constants
<br \><br \>
<i>Doctrine::PORTABILITY_ALL (default)</i>
<br \><br \>
turn on all portability features. this is the default setting.
<br \><br \>
<i>Doctrine::PORTABILITY_DELETE_COUNT</i>
<br \><br \>
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.
<br \><br \>
<i>Doctrine::PORTABILITY_EMPTY_TO_NULL</i>
<br \><br \>
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.
<br \><br \>
<i>Doctrine::PORTABILITY_ERRORS</i>
<br \><br \>
Makes certain error messages in certain drivers compatible with those from other DBMS's
<br \><br \>
Table 33-1. Error Code Re-mappings
Driver Description Old Constant New Constant
mysql, mysqli unique and primary key constraints Doctrine::ERROR_ALREADY_EXISTS Doctrine::ERROR_CONSTRAINT
mysql, mysqli not-null constraints Doctrine::ERROR_CONSTRAINT Doctrine::ERROR_CONSTRAINT_NOT_NULL
<br \><br \>
<i>Doctrine::PORTABILITY_FIX_ASSOC_FIELD_NAMES</i>
<br \><br \>
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.
<br \><br \>
<i>Doctrine::PORTABILITY_FIX_CASE</i>
<br \><br \>
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
<br \><br \>
<i>Doctrine::PORTABILITY_NONE</i>
<br \><br \>
Turn off all portability features
<br \><br \>
<i>Doctrine::PORTABILITY_NUMROWS</i>
<br \><br \>
Enable hack that makes numRows() work in Oracle
<br \><br \>
<i>Doctrine::PORTABILITY_RTRIM</i>
<br \><br \>
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.
<br \><br \>
Using setAttribute() to enable portability for lowercasing and trimming
<br \><br \>
<?php
renderCode("<?php
\$conn->setAttribute('portability',
Doctrine::PORTABILITY_FIX_CASE | Doctrine::PORTABILITY_RTRIM);
?>");
?>
<br \><br \>
Using setAttribute() to enable all portability options except trimming
<br \><br \>
<?php
renderCode("<?php
\$conn->setAttribute('portability',
Doctrine::PORTABILITY_ALL ^ Doctrine::PORTABILITY_RTRIM);
?>");
?>
<?php ?>
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. PEAR 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
Table 33-1. Error Code Re-mappings
Driver Description Old Constant New Constant
mysql, mysqli unique and primary key constraints Doctrine::ERROR_ALREADY_EXISTS Doctrine::ERROR_CONSTRAINT
mysql, mysqli not-null constraints Doctrine::ERROR_CONSTRAINT Doctrine::ERROR_CONSTRAINT_NOT_NULL
//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_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.
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>
<code type="php">
// setting default lockmode
$manager->setAttribute(Doctrine::ATTR_LOCKMODE, Doctrine::LOCK_PESSIMISTIC);
</code>
<code type="php">
// setting default lockmode
$manager->setAttribute(Doctrine::ATTR_LOCKMODE, Doctrine::LOCK_PESSIMISTIC);
</code>
<code type="php">
// turns automatic table creation off
$manager->setAttribute(Doctrine::ATTR_CREATE_TABLES, false);
</code>
<code type="php">
// turns automatic table creation off
$manager->setAttribute(Doctrine::ATTR_CREATE_TABLES, false);
</code>
<code type="php">
// turns transactional validation on
$manager->setAttribute(Doctrine::ATTR_VLD, true);
</code>
<code type="php">
// turns transactional validation on
$manager->setAttribute(Doctrine::ATTR_VLD, true);
</code>
<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">
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">
// 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">
// using sequences
class User extends Doctrine_Record {
public function setUp() {
$this->setSequenceName("user_seq");
}
}
</code>
<?php ?>
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.
<br \> <br \>
<?php
renderCode("<?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();
?>");
?>
<?php ?>
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 http://www.php.net/manual/en/function.PDO-construct.php.
The DSN consists in the following parts:
**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 get separated by &. 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:
`` phptype(dbsyntax)://username:password@protocol+hostspec/database?option=value ``
Most variations are allowed:
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
The currently supported database backends are:
||//fbsql//|| -> FrontBase ||
||//ibase//|| -> InterBase / Firebird (requires PHP 5) ||
||//mssql//|| -> Microsoft SQL Server (NOT for Sybase. Compile PHP --with-mssql) ||
||//mysql//|| -> MySQL ||
||//mysqli//|| -> MySQL (supports new authentication protocol) (requires PHP 5) ||
||//oci8 //|| -> Oracle 7/8/9/10 ||
||//pgsql//|| -> PostgreSQL ||
||//querysim//|| -> QuerySim ||
||//sqlite//|| -> SQLite 2 ||
A second DSN format is supported phptype(syntax)://user:pass@protocol(proto_opts)/database
If your database, option values, username or password contain characters used to delineate DSN parts, you can escape them via URI hex encodings:
``: = %3a``
``/ = %2f``
``@ = %40``
``+ = %2b``
``( = %28``
``) = %29``
``? = %3f``
``= = %3d``
``& = %26``
Warning
Please note, that some features may be not supported by all database backends.
Example
**Example 1.** Connect to database through a socket
mysql://user@unix(/path/to/socket)/pear
**Example 2.** Connect to database on a non standard port
pgsql://user:pass@tcp(localhost:5555)/pear
**Example 3.** Connect to SQLite on a Unix machine using options
sqlite:////full/unix/path/to/file.db?mode=0666
**Example 4.** Connect to SQLite on a Windows machine using options
sqlite:///c:/full/windows/path/to/file.db?mode=0666
**Example 5.** Connect to MySQLi using SSL
mysqli://user:pass@localhost/pear?key=client-key.pem&cert=client-cert.pem
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 http://www.php.net/manual/en/function.PDO-construct.php.
The DSN consists in the following parts:
**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 get separated by &. 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:
`` phptype(dbsyntax)://username:password@protocol+hostspec/database?option=value ``
Most variations are allowed:
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
The currently supported database backends are:
||//fbsql//|| -> FrontBase ||
||//ibase//|| -> InterBase / Firebird (requires PHP 5) ||
||//mssql//|| -> Microsoft SQL Server (NOT for Sybase. Compile PHP --with-mssql) ||
||//mysql//|| -> MySQL ||
||//mysqli//|| -> MySQL (supports new authentication protocol) (requires PHP 5) ||
||//oci8 //|| -> Oracle 7/8/9/10 ||
||//pgsql//|| -> PostgreSQL ||
||//querysim//|| -> QuerySim ||
||//sqlite//|| -> SQLite 2 ||
A second DSN format is supported phptype(syntax)://user:pass@protocol(proto_opts)/database
If your database, option values, username or password contain characters used to delineate DSN parts, you can escape them via URI hex encodings:
``: = %3a``
``/ = %2f``
``@ = %40``
``+ = %2b``
``( = %28``
``) = %29``
``? = %3f``
``= = %3d``
``& = %26``
Warning
Please note, that some features may be not supported by all database backends.
Example
**Example 1.** Connect to database through a socket
mysql://user@unix(/path/to/socket)/pear
**Example 2.** Connect to database on a non standard port
pgsql://user:pass@tcp(localhost:5555)/pear
**Example 3.** Connect to SQLite on a Unix machine using options
sqlite:////full/unix/path/to/file.db?mode=0666
**Example 4.** Connect to SQLite on a Windows machine using options
sqlite:///c:/full/windows/path/to/file.db?mode=0666
**Example 5.** Connect to MySQLi using SSL
mysqli://user:pass@localhost/pear?key=client-key.pem&cert=client-cert.pem
<?php ?>
Lazy-connecting to database is handled via Doctrine_Db wrapper. When using Doctrine_Db instead of PDO / Doctrine_Adapter, lazy-connecting
to database is being performed (that means Doctrine will only connect to database when needed). <br \><br \>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.
<br \> <br \>
<?php
renderCode("<?php
// we may use PDO / PEAR like DSN
// here we use PEAR like DSN
\$dbh = new Doctrine_Db('mysql://username:password@localhost/test');
// !! no actual database connection yet !!
// initalize a new Doctrine_Connection
\$conn = Doctrine_Manager::connection(\$dbh);
// !! no actual database connection yet !!
// connects database and performs a query
\$conn->query('FROM User u');
?>");
?>
<?php ?>
Lazy-connecting to database is handled via Doctrine_Db wrapper. When using Doctrine_Db instead of PDO / Doctrine_Adapter, lazy-connecting
to database is being performed (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">
// we may use PDO / PEAR like DSN
// here we use PEAR like DSN
\$dbh = new Doctrine_Db('mysql://username:password@localhost/test');
// !! no actual database connection yet !!
// initalize a new Doctrine_Connection
\$conn = Doctrine_Manager::connection(\$dbh);
// !! no actual database connection yet !!
// connects database and performs a query
\$conn->query('FROM User u');
?></code>
<?php ?>
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.
<br \><br \>
<?php
renderCode("<?php
// Doctrine_Manager controls all the connections
\$manager = Doctrine_Manager::getInstance();
// open first connection
\$conn = \$manager->openConnection(new PDO('dsn','username','password'), 'connection 1');
?>
");
?>
<br \><br \>
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.
<br \><br \>
<?php
renderCode("<?php
// open first connection
\$conn = Doctrine_Manager::connection(new PDO('dsn','username','password'), 'connection 1');
\$conn2 = Doctrine_Manager::connection();
// \$conn2 == \$conn
?>
");
?>
<br \><br \>
The current connection is the lastly opened connection.
<br \><br \>
<?php
renderCode("<?php
// open second connection
\$conn2 = \$manager->openConnection(new PDO('dsn2','username2','password2'), 'connection 2');
\$manager->getCurrentConnection(); // \$conn2
?>");
?>
<br \><br \>
You can change the current connection by calling setCurrentConnection().
<br \><br \>
<?php
renderCode("<?php
\$manager->setCurrentConnection('connection 1');
\$manager->getCurrentConnection(); // \$conn
?>
");
?>
<br \><br \>
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.
<br \><br \>
<?php
renderCode("<?php
// iterating through connections
foreach(\$manager as \$conn) {
}
?>");
?>
<?php ?>
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>
<?php ?>
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:
<br \> <br \>
<?php
renderCode("<?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();
}
?>");
?>
<br \><br \>
If your database extension isn't supported by PDO you can use special Doctrine_Adapter class (if availible). The following example uses db2 adapter:
<br \><br \>
<?php
renderCode("<?php
\$dsn = 'db2:dbname=testdb;host=127.0.0.1';
\$user = 'dbuser';
\$password = 'dbpass';
try {
\$dbh = Doctrine_Adapter::connect(\$dsn, \$user, \$password);
} catch (PDOException \$e) {
echo 'Connection failed: ' . \$e->getMessage();
}
?>");
?>
<br \><br \>
The next step is opening a new Doctrine_Connection.
<br \><br \>
<?php
renderCode("<?php
\$conn = Doctrine_Manager::connection(\$dbh);
?>");
?>
<?php ?>
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>
If your database extension isn't supported by PDO you can use special Doctrine_Adapter class (if availible). The following example uses db2 adapter:
<code type="php">
\$dsn = 'db2:dbname=testdb;host=127.0.0.1';
\$user = 'dbuser';
\$password = 'dbpass';
try {
\$dbh = Doctrine_Adapter::connect(\$dsn, \$user, \$password);
} catch (PDOException \$e) {
echo 'Connection failed: ' . \$e->getMessage();
}
?></code>
The next step is opening a new Doctrine_Connection.
<code type="php">
\$conn = Doctrine_Manager::connection(\$dbh);
?></code>
<?php ?>
Doctrine_Export drivers provide an easy database portable way of altering existing database tables.
<br \><br \>
NOTE: if you only want to get the generated sql (and not execute it) use Doctrine_Export::alterTableSql()
<br \><br \>
<?php
renderCode("<?php
\$dbh = new PDO('dsn','username','pw');
\$conn = Doctrine_Manager::getInstance()
->openConnection(\$dbh);
\$a = array('add' => array('name' => array('type' => 'string', 'length' => 255)));
\$conn->export->alterTableSql('mytable', \$a);
// On mysql this method returns:
// ALTER TABLE mytable ADD COLUMN name VARCHAR(255)
?>");
?>
<br \><br \>
Doctrine_Export::alterTable() takes two parameters:
<br \><br \>
string <i>$name</i>
<dd>name of the table that is intended to be changed. <br \>
array <i>$changes</i>
<dd>associative array that contains the details of each type of change that is intended to be performed.
The types of changes that are currently supported are defined as follows:
<ul>
<li \><i>name</i>
New name for the table.
<li \><i>add</i>
Associative array with the names of fields to be added as indexes of the array. The value of each entry of the array should be set to another associative array with the properties of the fields to be added. The properties of the fields should be the same as defined by the Doctrine parser.
<li \><i>remove</i>
Associative array with the names of fields to be removed as indexes of the array. Currently the values assigned to each entry are ignored. An empty array should be used for future compatibility.
<li \><i>rename</i>
Associative array with the names of fields to be renamed as indexes of the array. The value of each entry of the array should be set to another associative array with the entry named name with the new field name and the entry named Declaration that is expected to contain the portion of the field declaration already in DBMS specific SQL code as it is used in the CREATE TABLE statement.
<li \><i>change</i>
Associative array with the names of the fields to be changed as indexes of the array. Keep in mind that if it is intended to change either the name of a field and any other properties, the change array entries should have the new names of the fields as array indexes.
</ul>
The value of each entry of the array should be set to another associative array with the properties of the fields to that are meant to be changed as array entries. These entries should be assigned to the new values of the respective properties. The properties of the fields should be the same as defined by the Doctrine parser.
<code type="php">
$a = array('name' => 'userlist',
'add' => array(
'quota' => array(
'type' => 'integer',
'unsigned' => 1
)
),
'remove' => array(
'file_limit' => array(),
'time_limit' => array()
),
'change' => array(
'name' => array(
'length' => '20',
'definition' => array(
'type' => 'text',
'length' => 20
)
)
),
'rename' => array(
'sex' => array(
'name' => 'gender',
'definition' => array(
'type' => 'text',
'length' => 1,
'default' => 'M'
)
)
)
);
$dbh = new PDO('dsn','username','pw');
$conn = Doctrine_Manager::getInstance()->openConnection($dbh);
$conn->export->alterTable('mytable', $a);
</code>
<?php ?>
Doctrine_Export drivers provide an easy database portable way of altering existing database tables.
NOTE: if you only want to get the generated sql (and not execute it) use Doctrine_Export::alterTableSql()
<code type="php">
\$dbh = new PDO('dsn','username','pw');
\$conn = Doctrine_Manager::getInstance()
->openConnection(\$dbh);
\$a = array('add' => array('name' => array('type' => 'string', 'length' => 255)));
\$conn->export->alterTableSql('mytable', \$a);
// On mysql this method returns:
// ALTER TABLE mytable ADD COLUMN name VARCHAR(255)
?></code>
Doctrine_Export::alterTable() takes two parameters:
: string //$name// : name of the table that is intended to be changed.
: array //$changes// : associative array that contains the details of each type of change that is intended to be performed.
The types of changes that are currently supported are defined as follows:
* //name//
New name for the table.
* //add//
Associative array with the names of fields to be added as indexes of the array. The value of each entry of the array should be set to another associative array with the properties of the fields to be added. The properties of the fields should be the same as defined by the Doctrine parser.
* //remove//
Associative array with the names of fields to be removed as indexes of the array. Currently the values assigned to each entry are ignored. An empty array should be used for future compatibility.
* //rename//
Associative array with the names of fields to be renamed as indexes of the array. The value of each entry of the array should be set to another associative array with the entry named name with the new field name and the entry named Declaration that is expected to contain the portion of the field declaration already in DBMS specific SQL code as it is used in the CREATE TABLE statement.
* //change//
Associative array with the names of the fields to be changed as indexes of the array. Keep in mind that if it is intended to change either the name of a field and any other properties, the change array entries should have the new names of the fields as array indexes.
The value of each entry of the array should be set to another associative array with the properties of the fields to that are meant to be changed as array entries. These entries should be assigned to the new values of the respective properties. The properties of the fields should be the same as defined by the Doctrine parser.
<code type="php">
$a = array('name' => 'userlist',
'add' => array(
'quota' => array(
'type' => 'integer',
'unsigned' => 1
)
),
'remove' => array(
'file_limit' => array(),
'time_limit' => array()
),
'change' => array(
'name' => array(
'length' => '20',
'definition' => array(
'type' => 'text',
'length' => 20
)
)
),
'rename' => array(
'sex' => array(
'name' => 'gender',
'definition' => array(
'type' => 'text',
'length' => 1,
'default' => 'M'
)
)
)
);
$dbh = new PDO('dsn','username','pw');
$conn = Doctrine_Manager::getInstance()->openConnection($dbh);
$conn->export->alterTable('mytable', $a);
</code>
<code type="php">
$dbh = new PDO('dsn','username','pw');
$conn = Doctrine_Manager::getInstance()->openConnection($dbh);
$fields = array('id' => array(
'type' => 'integer',
'autoincrement' => true),
'name' => array(
'type' => 'string',
'fixed' => true,
'length' => 8)
);
// the following option is mysql specific and
// skipped by other drivers
$options = array('type' => 'MYISAM');
$conn->export->createTable('mytable', $fields);
// on mysql this executes query:
// CREATE TABLE mytable (id INT AUTO_INCREMENT PRIMARY KEY,
// name CHAR(8));
</code>
<code type="php">
$dbh = new PDO('dsn','username','pw');
$conn = Doctrine_Manager::getInstance()->openConnection($dbh);
$fields = array('id' => array(
'type' => 'integer',
'autoincrement' => true),
'name' => array(
'type' => 'string',
'fixed' => true,
'length' => 8)
);
// the following option is mysql specific and
// skipped by other drivers
$options = array('type' => 'MYISAM');
$conn->export->createTable('mytable', $fields);
// on mysql this executes query:
// CREATE TABLE mytable (id INT AUTO_INCREMENT PRIMARY KEY,
// name CHAR(8));
</code>
Syntax:
<div class='sql'>
<pre>
operand comparison_operator ANY (subquery)
operand comparison_operator SOME (subquery)
operand comparison_operator ALL (subquery)
</pre>
</div>
An ALL conditional expression returns true if the comparison operation is true for all values
in the result of the subquery or the result of the subquery is empty. An ALL conditional expression
is false if the result of the comparison is false for at least one row, and is unknown if neither true nor
false.
<br \><br \>
<div class='sql'>
<pre>
FROM C WHERE C.col1 < ALL (FROM C2(col1))
</pre>
</div>
An ANY conditional expression returns true if the comparison operation is true for some
value in the result of the subquery. An ANY conditional expression is false if the result of the subquery
is empty or if the comparison operation is false for every value in the result of the subquery, and is
unknown if neither true nor false.
<div class='sql'>
<pre>
FROM C WHERE C.col1 > ANY (FROM C2(col1))
</pre>
</div>
The keyword SOME is an alias for ANY.
<div class='sql'>
<pre>
FROM C WHERE C.col1 > SOME (FROM C2(col1))
</pre>
</div>
<br \>
The comparison operators that can be used with ALL or ANY conditional expressions are =, <, <=, >, >=, <>. The
result of the subquery must be same type with the conditional expression.
<br \><br \>
NOT IN is an alias for <> ALL. Thus, these two statements are equal:
<br \><br \>
<div class='sql'>
<pre>
FROM C WHERE C.col1 <> ALL (FROM C2(col1));
FROM C WHERE C.col1 NOT IN (FROM C2(col1));
</pre>
</div>
Syntax:
<code>
operand comparison_operator ANY (subquery)
operand comparison_operator SOME (subquery)
operand comparison_operator ALL (subquery)
</code>
An ALL conditional expression returns true if the comparison operation is true for all values
in the result of the subquery or the result of the subquery is empty. An ALL conditional expression
is false if the result of the comparison is false for at least one row, and is unknown if neither true nor
false.
<code>
FROM C WHERE C.col1 < ALL (FROM C2(col1))
</code>
An ANY conditional expression returns true if the comparison operation is true for some
value in the result of the subquery. An ANY conditional expression is false if the result of the subquery
is empty or if the comparison operation is false for every value in the result of the subquery, and is
unknown if neither true nor false.
<code>
FROM C WHERE C.col1 > ANY (FROM C2(col1))
</code>
The keyword SOME is an alias for ANY.
<code>
FROM C WHERE C.col1 > SOME (FROM C2(col1))
</code>
The comparison operators that can be used with ALL or ANY conditional expressions are =, <, <=, >, >=, <>. The
result of the subquery must be same type with the conditional expression.
NOT IN is an alias for <> ALL. Thus, these two statements are equal:
<code>
FROM C WHERE C.col1 <> ALL (FROM C2(col1));
FROM C WHERE C.col1 NOT IN (FROM C2(col1));
</code>
Syntax:
<div class='sql'>
<pre>
<i>operand</i> [NOT ]EXISTS (<i>subquery</i>)
</pre>
</div>
The EXISTS operator returns TRUE if the subquery returns one or more rows and FALSE otherwise. <br \>
<br \>
The NOT EXISTS operator returns TRUE if the subquery returns 0 rows and FALSE otherwise.<br \>
<br \>
Finding all articles which have readers:
<div class='sql'>
<pre>
FROM Article
WHERE EXISTS (FROM ReaderLog(id)
WHERE ReaderLog.article_id = Article.id)
</pre>
</div>
Finding all articles which don't have readers:
<div class='sql'>
<pre>
FROM Article
WHERE NOT EXISTS (FROM ReaderLog(id)
WHERE ReaderLog.article_id = Article.id)
</pre>
</div>
Syntax:
<code>
//operand// [NOT ]EXISTS (//subquery//)
</code>
The EXISTS operator returns TRUE if the subquery returns one or more rows and FALSE otherwise.
The NOT EXISTS operator returns TRUE if the subquery returns 0 rows and FALSE otherwise.
Finding all articles which have readers:
<code>
FROM Article
WHERE EXISTS (FROM ReaderLog(id)
WHERE ReaderLog.article_id = Article.id)
</code>
Finding all articles which don't have readers:
<code>
FROM Article
WHERE NOT EXISTS (FROM ReaderLog(id)
WHERE ReaderLog.article_id = Article.id)
</code>
Syntax:
<div class='sql'>
<pre>
<i>operand</i> IN (<i>subquery</i>|<i>value list</i>)
</pre>
</div>
An IN conditional expression returns true if the <i>operand</i> is found from result of the <i>subquery</i>
or if its in the specificied comma separated <i>value list</i>, hence the IN expression is always false if the result of the subquery
is empty.
When <i>value list</i> is being used there must be at least one element in that list.
<div class='sql'>
<pre>
FROM C1 WHERE C1.col1 IN (FROM C2(col1));
FROM User WHERE User.id IN (1,3,4,5)
</pre>
</div>
The keyword IN is an alias for = ANY. Thus, these two statements are equal:
<div class='sql'>
<pre>
FROM C1 WHERE C1.col1 = ANY (FROM C2(col1));
FROM C1 WHERE C1.col1 IN (FROM C2(col1));
</pre>
</div>
Syntax:
<code>
//operand// IN (//subquery//|//value list//)
</code>
An IN conditional expression returns true if the //operand// is found from result of the //subquery//
or if its in the specificied comma separated //value list//, hence the IN expression is always false if the result of the subquery
is empty.
When //value list// is being used there must be at least one element in that list.
<code>
FROM C1 WHERE C1.col1 IN (FROM C2(col1));
FROM User WHERE User.id IN (1,3,4,5)
</code>
The keyword IN is an alias for = ANY. Thus, these two statements are equal:
<code>
FROM C1 WHERE C1.col1 = ANY (FROM C2(col1));
FROM C1 WHERE C1.col1 IN (FROM C2(col1));
</code>
<code type="php">
// POSITIONAL PARAMETERS:
$users = $conn->query("FROM User WHERE User.name = ?", array('Arnold'));
$users = $conn->query("FROM User WHERE User.id > ? AND User.name LIKE ?", array(50, 'A%'));
// NAMED PARAMETERS:
$users = $conn->query("FROM User WHERE User.name = :name", array(':name' => 'Arnold'));
$users = $conn->query("FROM User WHERE User.id > :id AND User.name LIKE :name", array(':id' => 50, ':name' => 'A%'));
</code>
<code type="php">
// POSITIONAL PARAMETERS:
$users = $conn->query("FROM User WHERE User.name = ?", array('Arnold'));
$users = $conn->query("FROM User WHERE User.id > ? AND User.name LIKE ?", array(50, 'A%'));
// NAMED PARAMETERS:
$users = $conn->query("FROM User WHERE User.name = :name", array(':name' => 'Arnold'));
$users = $conn->query("FROM User WHERE User.id > :id AND User.name LIKE :name", array(':id' => 50, ':name' => 'A%'));
</code>
Syntax:<br \>
string_expression [NOT] LIKE pattern_value [ESCAPE escape_character]
<br \>
<br \>
The string_expression must have a string value. The pattern_value is a string literal or a string-valued
input parameter in which an underscore (_) stands for any single character, a percent (%) character
stands for any sequence of characters (including the empty sequence), and all other characters stand for
themselves. The optional escape_character is a single-character string literal or a character-valued
input parameter (i.e., char or Character) and is used to escape the special meaning of the underscore
and percent characters in pattern_value.
<br \><br \>
Examples:
<br \>
<ul>
<li \>address.phone LIKE 12%3 is true for '123' '12993' and false for '1234'
<li \>asentence.word LIKE l_se is true for lose and false for 'loose'
<li \>aword.underscored LIKE \_% ESCAPE '\' is true for '_foo' and false for 'bar'
<li \>address.phone NOT LIKE ‘12%3’ is false for '123' and '12993' and true for '1234'
</ul>
<br \>
If the value of the string_expression or pattern_value is NULL or unknown, the value of the LIKE
expression is unknown. If the escape_characteris specified and is NULL, the value of the LIKE expression
is unknown.
<code type="php">
// finding all users whose email ends with '@gmail.com'
$users = $conn->query("FROM User u, u.Email e WHERE e.address LIKE '%@gmail.com'");
// finding all users whose name starts with letter 'A'
$users = $conn->query("FROM User u WHERE u.name LIKE 'A%'");
</code>
Syntax:
string_expression [NOT] LIKE pattern_value [ESCAPE escape_character]
The string_expression must have a string value. The pattern_value is a string literal or a string-valued
input parameter in which an underscore (_) stands for any single character, a percent (%) character
stands for any sequence of characters (including the empty sequence), and all other characters stand for
themselves. The optional escape_character is a single-character string literal or a character-valued
input parameter (i.e., char or Character) and is used to escape the special meaning of the underscore
and percent characters in pattern_value.
Examples:
* address.phone LIKE 12%3 is true for '123' '12993' and false for '1234'
* asentence.word LIKE l_se is true for lose and false for 'loose'
* aword.underscored LIKE \_% ESCAPE '\' is true for '_foo' and false for 'bar'
* address.phone NOT LIKE ‘12%3’ is false for '123' and '12993' and true for '1234'
If the value of the string_expression or pattern_value is NULL or unknown, the value of the LIKE
expression is unknown. If the escape_characteris specified and is NULL, the value of the LIKE expression
is unknown.
<code type="php">
// finding all users whose email ends with '@gmail.com'
$users = $conn->query("FROM User u, u.Email e WHERE e.address LIKE '%@gmail.com'");
// finding all users whose name starts with letter 'A'
$users = $conn->query("FROM User u WHERE u.name LIKE 'A%'");
</code>
<b>Strings</b><br \>
A string literal is enclosed in single quotes—for example: 'literal'. A string literal that includes a single
quote is represented by two single quotes—for example: 'literal''s'.
<div class='sql'>
<pre>
FROM User WHERE User.name = 'Vincent'
</pre>
</div>
<b>Integers</b><br \>
Integer literals support the use of PHP integer literal syntax.
<div class='sql'>
<pre>
FROM User WHERE User.id = 4
</pre>
</div>
<b>Floats</b><br \>
Float literals support the use of PHP float literal syntax.
<div class='sql'>
<pre>
FROM Account WHERE Account.amount = 432.123
</pre>
</div>
<br \>
<b>Booleans</b><br \>
The boolean literals are true and false.
<div class='sql'>
<pre>
FROM User WHERE User.admin = true
FROM Session WHERE Session.is_authed = false
</pre>
</div>
<br \>
<b>Enums</b><br \>
The enumerated values work in the same way as string literals.
<div class='sql'>
<pre>
FROM User WHERE User.type = 'admin'
</pre>
</div>
<br \>
Predefined reserved literals are case insensitive, although its a good standard to write them in uppercase.
**Strings**
A string literal is enclosed in single quotesfor example: 'literal'. A string literal that includes a single
quote is represented by two single quotesfor example: 'literal''s'.
<code>
FROM User WHERE User.name = 'Vincent'
</code>
**Integers**
Integer literals support the use of PHP integer literal syntax.
<code>
FROM User WHERE User.id = 4
</code>
**Floats**
Float literals support the use of PHP float literal syntax.
<code>
FROM Account WHERE Account.amount = 432.123
</code>
**Booleans**
The boolean literals are true and false.
<code>
FROM User WHERE User.admin = true
FROM Session WHERE Session.is_authed = false
</code>
**Enums**
The enumerated values work in the same way as string literals.
<code>
FROM User WHERE User.type = 'admin'
</code>
Predefined reserved literals are case insensitive, although its a good standard to write them in uppercase.
The operators are listed below in order of decreasing precedence.
<ul>
<li \> Navigation operator (.)
<li \> Arithmetic operators: <br \>
+, - unary <br \>
*, / multiplication and division <br \>
+, - addition and subtraction <br \>
<li \> Comparison operators : =, >, >=, <, <=, <> (not equal), [NOT] LIKE, <br \>
[NOT] IN, IS [NOT] NULL, IS [NOT] EMPTY <br \>
<li \> Logical operators:<br \>
NOT <br \>
AND <br \>
OR <br \>
</ul>
The operators are listed below in order of decreasing precedence.
* Navigation operator (.)
* Arithmetic operators:
+, - unary
*, / multiplication and division
+, - addition and subtraction
* Comparison operators : =, >, >=, <, <=, <> (not equal), [NOT] LIKE,
[NOT] IN, IS [NOT] NULL, IS [NOT] EMPTY
* Logical operators:
NOT
AND
OR
A subquery can contain any of the keywords or clauses that an ordinary SELECT query can contain.
<br \><br \>
Some advantages of the subqueries:
<ul>
<li \>They allow queries that are structured so that it is possible to isolate each part of a statement.
<li \>They provide alternative ways to perform operations that would otherwise require complex joins and unions.
<li \>They are, in many people's opinion, readable. Indeed, it was the innovation of subqueries that gave people the original idea of calling the early SQL “Structured Query Language.”
</ul>
<code type="php">
// finding all users which don't belong to any group 1
$query = "FROM User WHERE User.id NOT IN
(SELECT u.id FROM User u
INNER JOIN u.Group g WHERE g.id = ?";
$users = $conn->query($query, array(1));
// finding all users which don't belong to any groups
// Notice:
// the usage of INNER JOIN
// the usage of empty brackets preceding the Group component
$query = "FROM User WHERE User.id NOT IN
(SELECT u.id FROM User u
INNER JOIN u.Group g)";
$users = $conn->query($query);
</code>
A subquery can contain any of the keywords or clauses that an ordinary SELECT query can contain.
Some advantages of the subqueries:
* They allow queries that are structured so that it is possible to isolate each part of a statement.
* They provide alternative ways to perform operations that would otherwise require complex joins and unions.
* They are, in many people's opinion, readable. Indeed, it was the innovation of subqueries that gave people the original idea of calling the early SQL “Structured Query Language.”
<code type="php">
// finding all users which don't belong to any group 1
$query = "FROM User WHERE User.id NOT IN
(SELECT u.id FROM User u
INNER JOIN u.Group g WHERE g.id = ?";
$users = $conn->query($query, array(1));
// finding all users which don't belong to any groups
// Notice:
// the usage of INNER JOIN
// the usage of empty brackets preceding the Group component
$query = "FROM User WHERE User.id NOT IN
(SELECT u.id FROM User u
INNER JOIN u.Group g)";
$users = $conn->query($query);
</code>
<div class='sql'>
<pre>
DELETE FROM <i>component_name</i>
[WHERE <i>where_condition</i>]
[ORDER BY ...]
[LIMIT <i>record_count</i>]
</pre>
</div>
<ul>
<li \>The DELETE statement deletes records from <i>component_name</i> and returns the number of records deleted.
<li \>The optional WHERE clause specifies the conditions that identify which records to delete.
Without WHERE clause, all records are deleted.
<li \>If the ORDER BY clause is specified, the records are deleted in the order that is specified.
<li \>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 <i>record_count</i> records.
</ul>
<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>
<code>
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>
Syntax: <br \>
<div class='sql'>
<pre>
FROM <i>component_reference</i> [[LEFT | INNER] JOIN <i>component_reference</i>] ...
</pre>
</div>
The FROM clause indicates the component or components from which to retrieve records.
If you name more than one component, you are performing a join.
For each table specified, you can optionally specify an alias.
<br \><br \>
<li \> The default join type is <i>LEFT JOIN</i>. This join can be indicated by the use of either 'LEFT JOIN' clause or simply ',', hence the following queries are equal:
<div class='sql'>
<pre>
SELECT u.*, p.* FROM User u LEFT JOIN u.Phonenumber
SELECT u.*, p.* FROM User u, u.Phonenumber p
</pre>
</div>
<li \><i>INNER JOIN</i> produces an intersection between two specified components (that is, each and every record in the first component is joined to each and every record in the second component).
So basically <i>INNER JOIN</i> can be used when you want to efficiently fetch for example all users which have one or more phonenumbers.
<div class='sql'>
<pre>
SELECT u.*, p.* FROM User u INNER JOIN u.Phonenumber p
</pre>
</div>
Syntax:
<code>
FROM //component_reference// [[LEFT | INNER] JOIN //component_reference//] ...
</code>
The FROM clause indicates the component or components from which to retrieve records.
If you name more than one component, you are performing a join.
For each table specified, you can optionally specify an alias.
* The default join type is //LEFT JOIN//. This join can be indicated by the use of either 'LEFT JOIN' clause or simply ',', hence the following queries are equal:
<code>
SELECT u.*, p.* FROM User u LEFT JOIN u.Phonenumber
SELECT u.*, p.* FROM User u, u.Phonenumber p
</code>
* //INNER JOIN// produces an intersection between two specified components (that is, each and every record in the first component is joined to each and every record in the second component).
So basically //INNER JOIN// can be used when you want to efficiently fetch for example all users which have one or more phonenumbers.
<code>
SELECT u.*, p.* FROM User u INNER JOIN u.Phonenumber p
</code>
<?php ?>
<ul>
<li \>The <i>CONCAT</i> function returns a string that is a concatenation of its arguments. In the example above we
map the concatenation of users firstname and lastname to a value called name
<br \><br \><?php
renderCode("<?php
\$q = new Doctrine_Query();
\$users = \$q->select('CONCAT(u.firstname, u.lastname) name')->from('User u')->execute();
foreach(\$users as \$user) {
// here 'name' is not a property of \$user,
// its a mapped function value
print \$user->name;
}
?>");
?>
<br \><br \>
<li \>The second and third arguments of the <i>SUBSTRING</i> function denote the starting position and length of
the substring to be returned. These arguments are integers. The first position of a string is denoted by 1.
The <i>SUBSTRING</i> function returns a string.
<br \><br \><?php
renderCode("<?php
\$q = new Doctrine_Query();
\$users = \$q->select('u.name')->from('User u')->where(\"SUBSTRING(u.name, 0, 1) = 'z'\")->execute();
foreach(\$users as \$user) {
print \$user->name;
}
?>");
?>
<br \><br \>
<li \>The <i>TRIM</i> function trims the specified character from a string. If the character to be trimmed is not
specified, it is assumed to be space (or blank). The optional trim_character is a single-character string
literal or a character-valued input parameter (i.e., char or Character)[30]. If a trim specification is
not provided, BOTH is assumed. The <i>TRIM</i> function returns the trimmed string.
<br \><br \><?php
renderCode("<?php
\$q = new Doctrine_Query();
\$users = \$q->select('u.name')->from('User u')->where(\"TRIM(u.name) = 'Someone'\")->execute();
foreach(\$users as \$user) {
print \$user->name;
}
?>");
?> <br \><br \>
<li \>The <i>LOWER</i> and <i>UPPER</i> functions convert a string to lower and upper case, respectively. They return a
string. <br \><br \>
<?php
renderCode("<?php
\$q = new Doctrine_Query();
\$users = \$q->select('u.name')->from('User u')->where(\"LOWER(u.name) = 'someone'\")->execute();
foreach(\$users as \$user) {
print \$user->name;
}
?>");
?> <br \><br \>
<li \>
The <i>LOCATE</i> function returns the position of a given string within a string, starting the search at a specified
position. It returns the first position at which the string was found as an integer. The first argument
is the string to be located; the second argument is the string to be searched; the optional third argument
is an integer that represents the string position at which the search is started (by default, the beginning of
the string to be searched). The first position in a string is denoted by 1. If the string is not found, 0 is
returned.
<br \><br \>
<li \>The <i>LENGTH</i> function returns the length of the string in characters as an integer.
</ul>
<?php ?>
* The //CONCAT// function returns a string that is a concatenation of its arguments. In the example above we
map the concatenation of users firstname and lastname to a value called name
<code type="php">
\$q = new Doctrine_Query();
\$users = \$q->select('CONCAT(u.firstname, u.lastname) name')->from('User u')->execute();
foreach(\$users as \$user) {
// here 'name' is not a property of \$user,
// its a mapped function value
print \$user->name;
}
?></code>
* The second and third arguments of the //SUBSTRING// function denote the starting position and length of
the substring to be returned. These arguments are integers. The first position of a string is denoted by 1.
The //SUBSTRING// function returns a string.
<code type="php">
\$q = new Doctrine_Query();
\$users = \$q->select('u.name')->from('User u')->where(\"SUBSTRING(u.name, 0, 1) = 'z'\")->execute();
foreach(\$users as \$user) {
print \$user->name;
}
?></code>
* The //TRIM// function trims the specified character from a string. If the character to be trimmed is not
specified, it is assumed to be space (or blank). The optional trim_character is a single-character string
literal or a character-valued input parameter (i.e., char or Character)[30]. If a trim specification is
not provided, BOTH is assumed. The //TRIM// function returns the trimmed string.
<code type="php">
\$q = new Doctrine_Query();
\$users = \$q->select('u.name')->from('User u')->where(\"TRIM(u.name) = 'Someone'\")->execute();
foreach(\$users as \$user) {
print \$user->name;
}
?></code>
* The //LOWER// and //UPPER// functions convert a string to lower and upper case, respectively. They return a
string.
<code type="php">
\$q = new Doctrine_Query();
\$users = \$q->select('u.name')->from('User u')->where(\"LOWER(u.name) = 'someone'\")->execute();
foreach(\$users as \$user) {
print \$user->name;
}
?></code>
*
The //LOCATE// function returns the position of a given string within a string, starting the search at a specified
position. It returns the first position at which the string was found as an integer. The first argument
is the string to be located; the second argument is the string to be searched; the optional third argument
is an integer that represents the string position at which the search is started (by default, the beginning of
the string to be searched). The first position in a string is denoted by 1. If the string is not found, 0 is
returned.
* The //LENGTH// function returns the length of the string in characters as an integer.
<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.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.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>
<code type="php">
$q = new Doctrine_Query();
$q->from('User')->where('User.Phonenumber.phonenumber.regexp(?,?)');
$users = $q->execute(array('[123]', '^[3-5]'));
</code>
<ul>
<li> GROUP BY and HAVING clauses can be used for dealing with aggregate functions
<br \>
<li> Following aggregate functions are availible on DQL: COUNT, MAX, MIN, AVG, SUM
<br \>
Selecting alphabetically first user by name.
<div class='sql'>
<pre>
SELECT MIN(u.name) FROM User u
</pre>
</div>
Selecting the sum of all Account amounts.
<div class='sql'>
<pre>
SELECT SUM(a.amount) FROM Account a
</pre>
</div>
<br \>
<li> Using an aggregate function in a statement containing no GROUP BY clause, results in grouping on all rows. In the example above
we fetch all users and the number of phonenumbers they have.
<div class='sql'>
<pre>
SELECT u.*, COUNT(p.id) FROM User u, u.Phonenumber p GROUP BY u.id
</pre>
</div>
<br \>
<li> The HAVING clause can be used for narrowing the results using aggregate values. In the following example we fetch
all users which have atleast 2 phonenumbers
<div class='sql'>
<pre>
SELECT u.* FROM User u, u.Phonenumber p HAVING COUNT(p.id) >= 2
</pre>
</div>
</ul>
<code type="php">
// retrieve all users and the phonenumber count for each user
$users = $conn->query("SELECT u.*, COUNT(p.id) count FROM User u, u.Phonenumber p GROUP BY u.id");
foreach($users as $user) {
print $user->name . ' has ' . $user->Phonenumber[0]->count . ' phonenumbers';
}
</code>
<li> GROUP BY and HAVING clauses can be used for dealing with aggregate functions
<li> Following aggregate functions are availible on DQL: COUNT, MAX, MIN, AVG, SUM
Selecting alphabetically first user by name.
<code>
SELECT MIN(u.name) FROM User u
</code>
Selecting the sum of all Account amounts.
<code>
SELECT SUM(a.amount) FROM Account a
</code>
<li> Using an aggregate function in a statement containing no GROUP BY clause, results in grouping on all rows. In the example above
we fetch all users and the number of phonenumbers they have.
<code>
SELECT u.*, COUNT(p.id) FROM User u, u.Phonenumber p GROUP BY u.id
</code>
<li> The HAVING clause can be used for narrowing the results using aggregate values. In the following example we fetch
all users which have atleast 2 phonenumbers
<code>
SELECT u.* FROM User u, u.Phonenumber p HAVING COUNT(p.id) >= 2
</code>
<code type="php">
// retrieve all users and the phonenumber count for each user
$users = $conn->query("SELECT u.*, COUNT(p.id) count FROM User u, u.Phonenumber p GROUP BY u.id");
foreach($users as $user) {
print $user->name . ' has ' . $user->Phonenumber[0]->count . ' phonenumbers';
}
</code>
Doctrine Query Language(DQL) is an Object Query Language created for helping users in complex object retrieval.
You should always consider using DQL(or raw SQL) when retrieving relational data efficiently (eg. when fetching users and their phonenumbers).
<br \><br \>
When compared to using raw SQL, DQL has several benefits: <br \>
<ul>
<li \>From the start it has been designed to retrieve records(objects) not result set rows
</ul>
<ul>
<li \>DQL understands relations so you don't have to type manually sql joins and join conditions
</ul>
<ul>
<li \>DQL is portable on different databases
</ul>
<ul>
<li \>DQL has some very complex built-in algorithms like (the record limit algorithm) which can help
developer to efficiently retrieve objects
</ul>
<ul>
<li \>It supports some functions that can save time when dealing with one-to-many, many-to-many relational data with conditional fetching.
</ul>
If the power of DQL isn't enough, you should consider using the rawSql API for object population.
<code type="php">
// DO NOT USE THE FOLLOWING CODE
// (using many sql queries for object population):
$users = $conn->getTable('User')->findAll();
foreach($users as $user) {
print $user->name."<br \>";
foreach($user->Phonenumber as $phonenumber) {
print $phonenumber."<br \>";
}
}
// same thing implemented much more efficiently:
// (using only one sql query for object population)
$users = $conn->query("FROM User.Phonenumber");
foreach($users as $user) {
print $user->name."<br \>";
foreach($user->Phonenumber as $phonenumber) {
print $phonenumber."<br \>";
}
}
</code>
Doctrine Query Language(DQL) is an Object Query Language created for helping users in complex object retrieval.
You should always consider using DQL(or raw SQL) when retrieving relational data efficiently (eg. when fetching users and their phonenumbers).
When compared to using raw SQL, DQL has several benefits:
* From the start it has been designed to retrieve records(objects) not result set rows
* DQL understands relations so you don't have to type manually sql joins and join conditions
* DQL is portable on different databases
* DQL has some very complex built-in algorithms like (the record limit algorithm) which can help
developer to efficiently retrieve objects
* It supports some functions that can save time when dealing with one-to-many, many-to-many relational data with conditional fetching.
If the power of DQL isn't enough, you should consider using the rawSql API for object population.
<code type="php">
// DO NOT USE THE FOLLOWING CODE
// (using many sql queries for object population):
$users = $conn->getTable('User')->findAll();
foreach($users as $user) {
print $user->name."
";
foreach($user->Phonenumber as $phonenumber) {
print $phonenumber."
";
}
}
// same thing implemented much more efficiently:
// (using only one sql query for object population)
$users = $conn->query("FROM User.Phonenumber");
foreach($users as $user) {
print $user->name."
";
foreach($user->Phonenumber as $phonenumber) {
print $phonenumber."
";
}
}
</code>
DQL LIMIT clause is portable on all supported databases. Special attention have been paid to following facts:
<br \><br \>
<li \> Only Mysql, Pgsql and Sqlite implement LIMIT / OFFSET clauses natively
<br \><br \>
<li \> In Oracle / Mssql / Firebird LIMIT / OFFSET clauses need to be emulated in driver specific way
<br \><br \>
<li \> The limit-subquery-algorithm needs to execute to subquery separately in mysql, since mysql doesn't yet support
LIMIT clause in subqueries<br \><br \>
<li \> Pgsql needs the order by fields to be preserved in SELECT clause, hence LS-algorithm needs to take this into consideration
when pgsql driver is used<br \><br \>
<li \> Oracle only allows < 30 object identifiers (= table/column names/aliases), hence the limit subquery must use as short aliases as possible
and it must avoid alias collisions with the main query.
DQL LIMIT clause is portable on all supported databases. Special attention have been paid to following facts:
* Only Mysql, Pgsql and Sqlite implement LIMIT / OFFSET clauses natively
* In Oracle / Mssql / Firebird LIMIT / OFFSET clauses need to be emulated in driver specific way
* The limit-subquery-algorithm needs to execute to subquery separately in mysql, since mysql doesn't yet support
LIMIT clause in subqueries
* Pgsql needs the order by fields to be preserved in SELECT clause, hence LS-algorithm needs to take this into consideration
when pgsql driver is used
* Oracle only allows < 30 object identifiers (= table/column names/aliases), hence the limit subquery must use as short aliases as possible
and it must avoid alias collisions with the main query.
Propably the most complex feature DQL parser has to offer is its LIMIT clause parser. Not only
does the DQL LIMIT clause parser take care of LIMIT database portability it is capable of limiting the number of records instead
of rows by using complex query analysis and subqueries.
Propably the most complex feature DQL parser has to offer is its LIMIT clause parser. Not only
does the DQL LIMIT clause parser take care of LIMIT database portability it is capable of limiting the number of records instead
of rows by using complex query analysis and subqueries.
The limit-subquery-algorithm is an algorithm that DQL parser uses internally when one-to-many / many-to-many relational
data is being fetched simultaneously. This kind of special algorithm is needed for the LIMIT clause to limit the number
of records instead of sql result set rows.
<br \><br \>
In the following example we have users and phonenumbers with their relation being one-to-many. Now lets say we want fetch the first 20 users
and all their related phonenumbers.
<br \><br \>
Now one might consider that adding a simple driver specific LIMIT 20 at the end of query would return the correct results.
Thats wrong, since we you might get anything between 1-20 users as the first user might have 20 phonenumbers and then record set would consist of 20 rows.
<br \><br \>
DQL overcomes this problem with subqueries and with complex but efficient subquery analysis. In the next example we are going to fetch first 20 users and all their phonenumbers with single efficient query.
Notice how the DQL parser is smart enough to use column aggregation inheritance even in the subquery and how its smart enough to use different aliases
for the tables in the subquery to avoid alias collisions.
<br \><br \>
DQL QUERY:
<div class='sql'><pre>
SELECT u.id, u.name, p.* FROM User u LEFT JOIN u.Phonenumber p LIMIT 20
</pre></div>
SQL QUERY:
<div class='sql'>
<pre>
SELECT
e.id AS e__id,
e.name AS e__name,
p.id AS p__id,
p.phonenumber AS p__phonenumber,
p.entity_id AS p__entity_id
FROM entity e
LEFT JOIN phonenumber p ON e.id = p.entity_id
WHERE e.id IN (
SELECT DISTINCT e2.id
FROM entity e2
WHERE (e2.type = 0) LIMIT 20) AND (e.type = 0)
</pre>
</div>
<br \><br \>
In the next example we are going to fetch first 20 users and all their phonenumbers and only
those users that actually have phonenumbers with single efficient query, hence we use an INNER JOIN.
Notice how the DQL parser is smart enough to use the INNER JOIN in the subquery.
<br \><br \>
DQL QUERY:
<div class='sql'><pre>
SELECT u.id, u.name, p.* FROM User u LEFT JOIN u.Phonenumber p LIMIT 20
</pre></div>
SQL QUERY:
<div class='sql'>
<pre>
SELECT
e.id AS e__id,
e.name AS e__name,
p.id AS p__id,
p.phonenumber AS p__phonenumber,
p.entity_id AS p__entity_id
FROM entity e
LEFT JOIN phonenumber p ON e.id = p.entity_id
WHERE e.id IN (
SELECT DISTINCT e2.id
FROM entity e2
INNER JOIN phonenumber p2 ON e2.id = p2.entity_id
WHERE (e2.type = 0) LIMIT 20) AND (e.type = 0)
</pre>
</div>
The limit-subquery-algorithm is an algorithm that DQL parser uses internally when one-to-many / many-to-many relational
data is being fetched simultaneously. This kind of special algorithm is needed for the LIMIT clause to limit the number
of records instead of sql result set rows.
In the following example we have users and phonenumbers with their relation being one-to-many. Now lets say we want fetch the first 20 users
and all their related phonenumbers.
Now one might consider that adding a simple driver specific LIMIT 20 at the end of query would return the correct results.
Thats wrong, since we you might get anything between 1-20 users as the first user might have 20 phonenumbers and then record set would consist of 20 rows.
DQL overcomes this problem with subqueries and with complex but efficient subquery analysis. In the next example we are going to fetch first 20 users and all their phonenumbers with single efficient query.
Notice how the DQL parser is smart enough to use column aggregation inheritance even in the subquery and how its smart enough to use different aliases
for the tables in the subquery to avoid alias collisions.
DQL QUERY:
<div class='sql'><pre>
SELECT u.id, u.name, p.* FROM User u LEFT JOIN u.Phonenumber p LIMIT 20
</pre></div>
SQL QUERY:
<code>
SELECT
e.id AS e__id,
e.name AS e__name,
p.id AS p__id,
p.phonenumber AS p__phonenumber,
p.entity_id AS p__entity_id
FROM entity e
LEFT JOIN phonenumber p ON e.id = p.entity_id
WHERE e.id IN (
SELECT DISTINCT e2.id
FROM entity e2
WHERE (e2.type = 0) LIMIT 20) AND (e.type = 0)
</code>
In the next example we are going to fetch first 20 users and all their phonenumbers and only
those users that actually have phonenumbers with single efficient query, hence we use an INNER JOIN.
Notice how the DQL parser is smart enough to use the INNER JOIN in the subquery.
DQL QUERY:
<div class='sql'><pre>
SELECT u.id, u.name, p.* FROM User u LEFT JOIN u.Phonenumber p LIMIT 20
</pre></div>
SQL QUERY:
<code>
SELECT
e.id AS e__id,
e.name AS e__name,
p.id AS p__id,
p.phonenumber AS p__phonenumber,
p.entity_id AS p__entity_id
FROM entity e
LEFT JOIN phonenumber p ON e.id = p.entity_id
WHERE e.id IN (
SELECT DISTINCT e2.id
FROM entity e2
INNER JOIN phonenumber p2 ON e2.id = p2.entity_id
WHERE (e2.type = 0) LIMIT 20) AND (e.type = 0)
</code>
<code type="php">
// retrieve the first 20 users and all their associated phonenumbers
$users = $conn->query("SELECT u.*, p.* FROM User u, u.Phonenumber p LIMIT 20");
foreach($users as $user) {
print ' --- '.$user->name.' --- \n';
foreach($user->Phonenumber as $p) {
print $p->phonenumber.'\n';
}
}
</code>
<code type="php">
// retrieve the first 20 users and all their associated phonenumbers
$users = $conn->query("SELECT u.*, p.* FROM User u, u.Phonenumber p LIMIT 20");
foreach($users as $user) {
print ' --- '.$user->name.' --- \n';
foreach($user->Phonenumber as $p) {
print $p->phonenumber.'\n';
}
}
</code>
Record collections can be sorted efficiently at the database level using the ORDER BY clause.
Syntax:
<div class='sql'>
<pre>
[ORDER BY {ComponentAlias.columnName}
[ASC | DESC], ...]
</pre>
</div>
Examples:
<br \>
<div class='sql'>
<pre>
FROM User.Phonenumber
ORDER BY User.name, Phonenumber.phonenumber
FROM User u, u.Email e
ORDER BY e.address, u.id
</pre>
</div>
In order to sort in reverse order you can add the DESC (descending) keyword to the name of the column in the ORDER BY clause that you are sorting by. The default is ascending order; this can be specified explicitly using the ASC keyword.
<br \>
<div class='sql'>
<pre>
FROM User u, u.Email e
ORDER BY e.address DESC, u.id ASC;
</pre>
</div>
Record collections can be sorted efficiently at the database level using the ORDER BY clause.
Syntax:
<code>
[ORDER BY {ComponentAlias.columnName}
[ASC | DESC], ...]
</code>
Examples:
<code>
FROM User.Phonenumber
ORDER BY User.name, Phonenumber.phonenumber
FROM User u, u.Email e
ORDER BY e.address, u.id
</code>
In order to sort in reverse order you can add the DESC (descending) keyword to the name of the column in the ORDER BY clause that you are sorting by. The default is ascending order; this can be specified explicitly using the ASC keyword.
<code>
FROM User u, u.Email e
ORDER BY e.address DESC, u.id ASC;
</code>
Aggregate value SELECT syntax:
Aggregate value SELECT syntax:
<code type="php">
// SELECT u.*, COUNT(p.id) num_posts FROM User u, u.Posts p WHERE u.id = 1 GROUP BY u.id
$query = new Doctrine_Query();
$query->select('u.*, COUNT(p.id) num_posts')
->from('User u, u.Posts p')
->where('u.id = ?', 1)
->groupby('u.id');
$users = $query->execute();
echo $users->Posts[0]->num_posts . ' posts found';
</code>
<code type="php">
// SELECT u.*, COUNT(p.id) num_posts FROM User u, u.Posts p WHERE u.id = 1 GROUP BY u.id
$query = new Doctrine_Query();
$query->select('u.*, COUNT(p.id) num_posts')
->from('User u, u.Posts p')
->where('u.id = ?', 1)
->groupby('u.id');
$users = $query->execute();
echo $users->Posts[0]->num_posts . ' posts found';
</code>
SELECT statement syntax:
<div class='sql'>
<pre>
SELECT
[ALL | DISTINCT]
<i>select_expr</i>, ...
[FROM <i>components</i>
[WHERE <i>where_condition</i>]
[GROUP BY <i>groupby_expr</i>
[ASC | DESC], ... ]
[HAVING <i>where_condition</i>]
[ORDER BY <i>orderby_expr</i>
[ASC | DESC], ...]
[LIMIT <i>row_count</i> OFFSET <i>offset</i>}]
</pre>
</div>
<br \>
The SELECT statement is used for the retrieval of data from one or more components.
<ul>
<li \>Each <i>select_expr</i> indicates a column or an aggregate function value that you want to retrieve. There must be at least one <i>select_expr</i> in every SELECT statement.
<div class='sql'>
<pre>
SELECT a.name, a.amount FROM Account a
</pre>
</div>
<li \>An asterisk can be used for selecting all columns from given component. Even when using an asterisk the executed sql queries never actually use it
(Doctrine converts asterisk to appropriate column names, hence leading to better performance on some databases).
<div class='sql'>
<pre>
SELECT a.* FROM Account a
</pre>
</div>
<li \>FROM clause <i>components</i> indicates the component or components from which to retrieve records.
<div class='sql'>
<pre>
SELECT a.* FROM Account a
SELECT u.*, p.*, g.* FROM User u LEFT JOIN u.Phonenumber p LEFT JOIN u.Group g
</pre>
</div>
<li \>The WHERE clause, if given, indicates the condition or conditions that the records must satisfy to be selected. <i>where_condition</i> is an expression that evaluates to true for each row to be selected. The statement selects all rows if there is no WHERE clause.
<div class='sql'>
<pre>
SELECT a.* FROM Account a WHERE a.amount > 2000
</pre>
</div>
<li \>In the WHERE clause, you can use any of the functions and operators that DQL supports, except for aggregate (summary) functions
<li \>The HAVING clause can be used for narrowing the results with aggregate functions
<div class='sql'>
<pre>
SELECT u.* FROM User u LEFT JOIN u.Phonenumber p HAVING COUNT(p.id) > 3
</pre>
</div>
<li \>The ORDER BY clause can be used for sorting the results
<div class='sql'>
<pre>
SELECT u.* FROM User u ORDER BY u.name
</pre>
</div>
<li \>The LIMIT and OFFSET clauses can be used for efficiently limiting the number of records to a given <i>row_count</i>
<div class='sql'>
<pre>
SELECT u.* FROM User u LIMIT 20
</pre>
</div>
</ul>
SELECT statement syntax:
<code>
SELECT
[ALL | DISTINCT]
//select_expr//, ...
[FROM //components//
[WHERE //where_condition//]
[GROUP BY //groupby_expr//
[ASC | DESC], ... ]
[HAVING //where_condition//]
[ORDER BY //orderby_expr//
[ASC | DESC], ...]
[LIMIT //row_count// OFFSET //offset//}]
</code>
The SELECT statement is used for the retrieval of data from one or more components.
* Each //select_expr// indicates a column or an aggregate function value that you want to retrieve. There must be at least one //select_expr// in every SELECT statement.
<code>
SELECT a.name, a.amount FROM Account a
</code>
* An asterisk can be used for selecting all columns from given component. Even when using an asterisk the executed sql queries never actually use it
(Doctrine converts asterisk to appropriate column names, hence leading to better performance on some databases).
<code>
SELECT a.* FROM Account a
</code>
* FROM clause //components// indicates the component or components from which to retrieve records.
<code>
SELECT a.* FROM Account a
SELECT u.*, p.*, g.* FROM User u LEFT JOIN u.Phonenumber p LEFT JOIN u.Group g
</code>
* The WHERE clause, if given, indicates the condition or conditions that the records must satisfy to be selected. //where_condition// is an expression that evaluates to true for each row to be selected. The statement selects all rows if there is no WHERE clause.
<code>
SELECT a.* FROM Account a WHERE a.amount > 2000
</code>
* In the WHERE clause, you can use any of the functions and operators that DQL supports, except for aggregate (summary) functions
* The HAVING clause can be used for narrowing the results with aggregate functions
<code>
SELECT u.* FROM User u LEFT JOIN u.Phonenumber p HAVING COUNT(p.id) > 3
</code>
* The ORDER BY clause can be used for sorting the results
<code>
SELECT u.* FROM User u ORDER BY u.name
</code>
* The LIMIT and OFFSET clauses can be used for efficiently limiting the number of records to a given //row_count//
<code>
SELECT u.* FROM User u LIMIT 20
</code>
UPDATE statement syntax:
<div class='sql'>
<pre>
UPDATE <i>component_name</i>
SET <i>col_name1</i>=<i>expr1</i> [, <i>col_name2</i>=<i>expr2</i> ...]
[WHERE <i>where_condition</i>]
[ORDER BY ...]
[LIMIT <i>record_count</i>]
</pre>
</div>
<ul>
<li \>The UPDATE statement updates columns of existing records in <i>component_name</i> with new values and returns the number of affected records.
<li \>The SET clause indicates which columns to modify and the values they should be given.
<li \>The optional WHERE clause specifies the conditions that identify which records to update.
Without WHERE clause, all records are updated.
<li \>The optional ORDER BY clause specifies the order in which the records are being updated.
<li \>The LIMIT clause places a limit on the number of records that can be updated. You can use LIMIT row_count to restrict the scope of the UPDATE.
A LIMIT clause is a <b>rows-matched restriction</b> not a rows-changed restriction.
The statement stops as soon as it has found <i>record_count</i> rows that satisfy the WHERE clause, whether or not they actually were changed.
</ul>
<code type="php">
$q = 'UPDATE Account SET amount = amount + 200 WHERE id > 200';
$rows = $this->conn->query($q);
// the same query using the query interface
$q = new Doctrine_Query();
$rows = $q->update('Account')
->set('amount', 'amount + 200')
->where('id > 200')
->execute();
print $rows; // the number of affected rows
</code>
UPDATE statement syntax:
<code>
UPDATE //component_name//
SET //col_name1//=//expr1// [, //col_name2//=//expr2// ...]
[WHERE //where_condition//]
[ORDER BY ...]
[LIMIT //record_count//]
</code>
* The UPDATE statement updates columns of existing records in //component_name// with new values and returns the number of affected records.
* The SET clause indicates which columns to modify and the values they should be given.
* The optional WHERE clause specifies the conditions that identify which records to update.
Without WHERE clause, all records are updated.
* The optional ORDER BY clause specifies the order in which the records are being updated.
* The LIMIT clause places a limit on the number of records that can be updated. You can use LIMIT row_count to restrict the scope of the UPDATE.
A LIMIT clause is a **rows-matched restriction** not a rows-changed restriction.
The statement stops as soon as it has found //record_count// rows that satisfy the WHERE clause, whether or not they actually were changed.
<code type="php">
$q = 'UPDATE Account SET amount = amount + 200 WHERE id > 200';
$rows = $this->conn->query($q);
// the same query using the query interface
$q = new Doctrine_Query();
$rows = $q->update('Account')
->set('amount', 'amount + 200')
->where('id > 200')
->execute();
print $rows; // the number of affected rows
</code>
<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">
$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>
This diff is collapsed.
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