advanced-configuration.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. Advanced Configuration
  2. ======================
  3. The configuration of the EntityManager requires a
  4. ``Doctrine\ORM\Configuration`` instance as well as some database
  5. connection parameters. This example shows all the potential
  6. steps of configuration.
  7. .. code-block:: php
  8. <?php
  9. use Doctrine\ORM\EntityManager,
  10. Doctrine\ORM\Configuration;
  11. // ...
  12. if ($applicationMode == "development") {
  13. $cache = new \Doctrine\Common\Cache\ArrayCache;
  14. } else {
  15. $cache = new \Doctrine\Common\Cache\ApcCache;
  16. }
  17. $config = new Configuration;
  18. $config->setMetadataCacheImpl($cache);
  19. $driverImpl = $config->newDefaultAnnotationDriver('/path/to/lib/MyProject/Entities');
  20. $config->setMetadataDriverImpl($driverImpl);
  21. $config->setQueryCacheImpl($cache);
  22. $config->setProxyDir('/path/to/myproject/lib/MyProject/Proxies');
  23. $config->setProxyNamespace('MyProject\Proxies');
  24. if ($applicationMode == "development") {
  25. $config->setAutoGenerateProxyClasses(true);
  26. } else {
  27. $config->setAutoGenerateProxyClasses(false);
  28. }
  29. $connectionOptions = array(
  30. 'driver' => 'pdo_sqlite',
  31. 'path' => 'database.sqlite'
  32. );
  33. $em = EntityManager::create($connectionOptions, $config);
  34. .. note::
  35. Do not use Doctrine without a metadata and query cache!
  36. Doctrine is optimized for working with caches. The main
  37. parts in Doctrine that are optimized for caching are the metadata
  38. mapping information with the metadata cache and the DQL to SQL
  39. conversions with the query cache. These 2 caches require only an
  40. absolute minimum of memory yet they heavily improve the runtime
  41. performance of Doctrine. The recommended cache driver to use with
  42. Doctrine is `APC <http://www.php.net/apc>`_. APC provides you with
  43. an opcode-cache (which is highly recommended anyway) and a very
  44. fast in-memory cache storage that you can use for the metadata and
  45. query caches as seen in the previous code snippet.
  46. Configuration Options
  47. ---------------------
  48. The following sections describe all the configuration options
  49. available on a ``Doctrine\ORM\Configuration`` instance.
  50. Proxy Directory (***REQUIRED***)
  51. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  52. .. code-block:: php
  53. <?php
  54. $config->setProxyDir($dir);
  55. $config->getProxyDir();
  56. Gets or sets the directory where Doctrine generates any proxy
  57. classes. For a detailed explanation on proxy classes and how they
  58. are used in Doctrine, refer to the "Proxy Objects" section further
  59. down.
  60. Proxy Namespace (***REQUIRED***)
  61. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  62. .. code-block:: php
  63. <?php
  64. $config->setProxyNamespace($namespace);
  65. $config->getProxyNamespace();
  66. Gets or sets the namespace to use for generated proxy classes. For
  67. a detailed explanation on proxy classes and how they are used in
  68. Doctrine, refer to the "Proxy Objects" section further down.
  69. Metadata Driver (***REQUIRED***)
  70. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  71. .. code-block:: php
  72. <?php
  73. $config->setMetadataDriverImpl($driver);
  74. $config->getMetadataDriverImpl();
  75. Gets or sets the metadata driver implementation that is used by
  76. Doctrine to acquire the object-relational metadata for your
  77. classes.
  78. There are currently 4 available implementations:
  79. - ``Doctrine\ORM\Mapping\Driver\AnnotationDriver``
  80. - ``Doctrine\ORM\Mapping\Driver\XmlDriver``
  81. - ``Doctrine\ORM\Mapping\Driver\YamlDriver``
  82. - ``Doctrine\ORM\Mapping\Driver\DriverChain``
  83. Throughout the most part of this manual the AnnotationDriver is
  84. used in the examples. For information on the usage of the XmlDriver
  85. or YamlDriver please refer to the dedicated chapters
  86. ``XML Mapping`` and ``YAML Mapping``.
  87. The annotation driver can be configured with a factory method on
  88. the ``Doctrine\ORM\Configuration``:
  89. .. code-block:: php
  90. <?php
  91. $driverImpl = $config->newDefaultAnnotationDriver('/path/to/lib/MyProject/Entities');
  92. $config->setMetadataDriverImpl($driverImpl);
  93. The path information to the entities is required for the annotation
  94. driver, because otherwise mass-operations on all entities through
  95. the console could not work correctly. All of metadata drivers
  96. accept either a single directory as a string or an array of
  97. directories. With this feature a single driver can support multiple
  98. directories of Entities.
  99. Metadata Cache (***RECOMMENDED***)
  100. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  101. .. code-block:: php
  102. <?php
  103. $config->setMetadataCacheImpl($cache);
  104. $config->getMetadataCacheImpl();
  105. Gets or sets the cache implementation to use for caching metadata
  106. information, that is, all the information you supply via
  107. annotations, xml or yaml, so that they do not need to be parsed and
  108. loaded from scratch on every single request which is a waste of
  109. resources. The cache implementation must implement the
  110. ``Doctrine\Common\Cache\Cache`` interface.
  111. Usage of a metadata cache is highly recommended.
  112. The recommended implementations for production are:
  113. - ``Doctrine\Common\Cache\ApcCache``
  114. - ``Doctrine\Common\Cache\MemcacheCache``
  115. - ``Doctrine\Common\Cache\XcacheCache``
  116. - ``Doctrine\Common\Cache\RedisCache``
  117. For development you should use the
  118. ``Doctrine\Common\Cache\ArrayCache`` which only caches data on a
  119. per-request basis.
  120. Query Cache (***RECOMMENDED***)
  121. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  122. .. code-block:: php
  123. <?php
  124. $config->setQueryCacheImpl($cache);
  125. $config->getQueryCacheImpl();
  126. Gets or sets the cache implementation to use for caching DQL
  127. queries, that is, the result of a DQL parsing process that includes
  128. the final SQL as well as meta information about how to process the
  129. SQL result set of a query. Note that the query cache does not
  130. affect query results. You do not get stale data. This is a pure
  131. optimization cache without any negative side-effects (except some
  132. minimal memory usage in your cache).
  133. Usage of a query cache is highly recommended.
  134. The recommended implementations for production are:
  135. - ``Doctrine\Common\Cache\ApcCache``
  136. - ``Doctrine\Common\Cache\MemcacheCache``
  137. - ``Doctrine\Common\Cache\XcacheCache``
  138. - ``Doctrine\Common\Cache\RedisCache``
  139. For development you should use the
  140. ``Doctrine\Common\Cache\ArrayCache`` which only caches data on a
  141. per-request basis.
  142. SQL Logger (***Optional***)
  143. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  144. .. code-block:: php
  145. <?php
  146. $config->setSQLLogger($logger);
  147. $config->getSQLLogger();
  148. Gets or sets the logger to use for logging all SQL statements
  149. executed by Doctrine. The logger class must implement the
  150. ``Doctrine\DBAL\Logging\SQLLogger`` interface. A simple default
  151. implementation that logs to the standard output using ``echo`` and
  152. ``var_dump`` can be found at
  153. ``Doctrine\DBAL\Logging\EchoSQLLogger``.
  154. Auto-generating Proxy Classes (***OPTIONAL***)
  155. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  156. .. code-block:: php
  157. <?php
  158. $config->setAutoGenerateProxyClasses($bool);
  159. $config->getAutoGenerateProxyClasses();
  160. Gets or sets whether proxy classes should be generated
  161. automatically at runtime by Doctrine. If set to ``FALSE``, proxy
  162. classes must be generated manually through the doctrine command
  163. line task ``generate-proxies``. The strongly recommended value for
  164. a production environment is ``FALSE``.
  165. Development vs Production Configuration
  166. ---------------------------------------
  167. You should code your Doctrine2 bootstrapping with two different
  168. runtime models in mind. There are some serious benefits of using
  169. APC or Memcache in production. In development however this will
  170. frequently give you fatal errors, when you change your entities and
  171. the cache still keeps the outdated metadata. That is why we
  172. recommend the ``ArrayCache`` for development.
  173. Furthermore you should have the Auto-generating Proxy Classes
  174. option to true in development and to false in production. If this
  175. option is set to ``TRUE`` it can seriously hurt your script
  176. performance if several proxy classes are re-generated during script
  177. execution. Filesystem calls of that magnitude can even slower than
  178. all the database queries Doctrine issues. Additionally writing a
  179. proxy sets an exclusive file lock which can cause serious
  180. performance bottlenecks in systems with regular concurrent
  181. requests.
  182. Connection Options
  183. ------------------
  184. The ``$connectionOptions`` passed as the first argument to
  185. ``EntityManager::create()`` has to be either an array or an
  186. instance of ``Doctrine\DBAL\Connection``. If an array is passed it
  187. is directly passed along to the DBAL Factory
  188. ``Doctrine\DBAL\DriverManager::getConnection()``. The DBAL
  189. configuration is explained in the
  190. `DBAL section <./../../../../../dbal/2.0/docs/reference/configuration/en>`_.
  191. Proxy Objects
  192. -------------
  193. A proxy object is an object that is put in place or used instead of
  194. the "real" object. A proxy object can add behavior to the object
  195. being proxied without that object being aware of it. In Doctrine 2,
  196. proxy objects are used to realize several features but mainly for
  197. transparent lazy-loading.
  198. Proxy objects with their lazy-loading facilities help to keep the
  199. subset of objects that are already in memory connected to the rest
  200. of the objects. This is an essential property as without it there
  201. would always be fragile partial objects at the outer edges of your
  202. object graph.
  203. Doctrine 2 implements a variant of the proxy pattern where it
  204. generates classes that extend your entity classes and adds
  205. lazy-loading capabilities to them. Doctrine can then give you an
  206. instance of such a proxy class whenever you request an object of
  207. the class being proxied. This happens in two situations:
  208. Reference Proxies
  209. ~~~~~~~~~~~~~~~~~
  210. The method ``EntityManager#getReference($entityName, $identifier)``
  211. lets you obtain a reference to an entity for which the identifier
  212. is known, without loading that entity from the database. This is
  213. useful, for example, as a performance enhancement, when you want to
  214. establish an association to an entity for which you have the
  215. identifier. You could simply do this:
  216. .. code-block:: php
  217. <?php
  218. // $em instanceof EntityManager, $cart instanceof MyProject\Model\Cart
  219. // $itemId comes from somewhere, probably a request parameter
  220. $item = $em->getReference('MyProject\Model\Item', $itemId);
  221. $cart->addItem($item);
  222. Here, we added an Item to a Cart without loading the Item from the
  223. database. If you invoke any method on the Item instance, it would
  224. fully initialize its state transparently from the database. Here
  225. $item is actually an instance of the proxy class that was generated
  226. for the Item class but your code does not need to care. In fact it
  227. **should not care**. Proxy objects should be transparent to your
  228. code.
  229. Association proxies
  230. ~~~~~~~~~~~~~~~~~~~
  231. The second most important situation where Doctrine uses proxy
  232. objects is when querying for objects. Whenever you query for an
  233. object that has a single-valued association to another object that
  234. is configured LAZY, without joining that association in the same
  235. query, Doctrine puts proxy objects in place where normally the
  236. associated object would be. Just like other proxies it will
  237. transparently initialize itself on first access.
  238. .. note::
  239. Joining an association in a DQL or native query
  240. essentially means eager loading of that association in that query.
  241. This will override the 'fetch' option specified in the mapping for
  242. that association, but only for that query.
  243. Generating Proxy classes
  244. ~~~~~~~~~~~~~~~~~~~~~~~~
  245. Proxy classes can either be generated manually through the Doctrine
  246. Console or automatically by Doctrine. The configuration option that
  247. controls this behavior is:
  248. .. code-block:: php
  249. <?php
  250. $config->setAutoGenerateProxyClasses($bool);
  251. $config->getAutoGenerateProxyClasses();
  252. The default value is ``TRUE`` for convenient development. However,
  253. this setting is not optimal for performance and therefore not
  254. recommended for a production environment. To eliminate the overhead
  255. of proxy class generation during runtime, set this configuration
  256. option to ``FALSE``. When you do this in a development environment,
  257. note that you may get class/file not found errors if certain proxy
  258. classes are not available or failing lazy-loads if new methods were
  259. added to the entity class that are not yet in the proxy class. In
  260. such a case, simply use the Doctrine Console to (re)generate the
  261. proxy classes like so:
  262. .. code-block:: php
  263. $ ./doctrine orm:generate-proxies
  264. Autoloading Proxies
  265. -------------------
  266. When you deserialize proxy objects from the session or any other storage
  267. it is necessary to have an autoloading mechanism in place for these classes.
  268. For implementation reasons Proxy class names are not PSR-0 compliant. This
  269. means that you have to register a special autoloader for these classes:
  270. .. code-block:: php
  271. <?php
  272. use Doctrine\ORM\Proxy\Autoloader;
  273. $proxyDir = "/path/to/proxies";
  274. $proxyNamespace = "MyProxies";
  275. Autoloader::register($proxyDir, $proxyNamespace);
  276. If you want to execute additional logic to intercept the proxy file not found
  277. state you can pass a closure as the third argument. It will be called with
  278. the arguments proxydir, namespace and className when the proxy file could not
  279. be found.
  280. Multiple Metadata Sources
  281. -------------------------
  282. When using different components using Doctrine 2 you may end up
  283. with them using two different metadata drivers, for example XML and
  284. YAML. You can use the DriverChain Metadata implementations to
  285. aggregate these drivers based on namespaces:
  286. .. code-block:: php
  287. <?php
  288. use Doctrine\ORM\Mapping\Driver\DriverChain;
  289. $chain = new DriverChain();
  290. $chain->addDriver($xmlDriver, 'Doctrine\Tests\Models\Company');
  291. $chain->addDriver($yamlDriver, 'Doctrine\Tests\ORM\Mapping');
  292. Based on the namespace of the entity the loading of entities is
  293. delegated to the appropriate driver. The chain semantics come from
  294. the fact that the driver loops through all namespaces and matches
  295. the entity class name against the namespace using a
  296. ``strpos() === 0`` call. This means you need to order the drivers
  297. correctly if sub-namespaces use different metadata driver
  298. implementations.
  299. Default Repository (***OPTIONAL***)
  300. -----------------------------------
  301. Specifies the FQCN of a subclass of the EntityRepository.
  302. That will be available for all entities without a custom repository class.
  303. .. code-block:: php
  304. <?php
  305. $config->setDefaultRepositoryClassName($fqcn);
  306. $config->getDefaultRepositoryClassName();
  307. The default value is ``Doctrine\ORM\EntityRepository``.
  308. Any repository class must be a subclass of EntityRepository otherwise you got an ORMException
  309. Setting up the Console
  310. ----------------------
  311. Doctrine uses the Symfony Console component for generating the command
  312. line interface. You can take a look at the ``vendor/bin/doctrine.php``
  313. script and the ``Doctrine\ORM\Tools\Console\ConsoleRunner`` command
  314. for inspiration how to setup the cli.
  315. In general the required code looks like this:
  316. .. code-block:: php
  317. <?php
  318. $cli = new Application('Doctrine Command Line Interface', \Doctrine\ORM\Version::VERSION);
  319. $cli->setCatchExceptions(true);
  320. $cli->setHelperSet($helperSet);
  321. Doctrine\ORM\Tools\Console\ConsoleRunner::addCommands($cli);
  322. $cli->run();