tools.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. Tools
  2. =====
  3. Doctrine Console
  4. ----------------
  5. The Doctrine Console is a Command Line Interface tool for simplifying common
  6. administration tasks during the development of a project that uses Doctrine 2.
  7. Take a look at the :doc:`Installation and Configuration <configuration>`
  8. chapter for more information how to setup the console command.
  9. Display Help Information
  10. ~~~~~~~~~~~~~~~~~~~~~~~~
  11. Type ``php vendor/bin/doctrine`` on the command line and you should see an
  12. overview of the available commands or use the --help flag to get
  13. information on the available commands. If you want to know more
  14. about the use of generate entities for example, you can call:
  15. .. code-block:: php
  16. $> php vendor/bin/doctrine orm:generate-entities --help
  17. Configuration
  18. ~~~~~~~~~~~~~
  19. Whenever the ``doctrine`` command line tool is invoked, it can
  20. access all Commands that were registered by developer. There is no
  21. auto-detection mechanism at work. The Doctrine binary
  22. already registers all the commands that currently ship with
  23. Doctrine DBAL and ORM. If you want to use additional commands you
  24. have to register them yourself.
  25. All the commands of the Doctrine Console require access to the EntityManager
  26. or DBAL Connection. You have to inject them into the console application
  27. using so called Helper-Sets. This requires either the ``db``
  28. or the ``em`` helpers to be defined in order to work correctly.
  29. Whenever you invoke the Doctrine binary the current folder is searched for a
  30. ``cli-config.php`` file. This file contains the project specific configuration:
  31. .. code-block:: php
  32. <?php
  33. $helperSet = new \Symfony\Component\Console\Helper\HelperSet(array(
  34. 'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($conn)
  35. ));
  36. $cli->setHelperSet($helperSet);
  37. When dealing with the ORM package, the EntityManagerHelper is
  38. required:
  39. .. code-block:: php
  40. <?php
  41. $helperSet = new \Symfony\Component\Console\Helper\HelperSet(array(
  42. 'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em)
  43. ));
  44. $cli->setHelperSet($helperSet);
  45. The HelperSet instance has to be generated in a separate file (i.e.
  46. ``cli-config.php``) that contains typical Doctrine bootstrap code
  47. and predefines the needed HelperSet attributes mentioned above. A
  48. sample ``cli-config.php`` file looks as follows:
  49. .. code-block:: php
  50. <?php
  51. // cli-config.php
  52. require_once 'my_bootstrap.php';
  53. // Any way to access the EntityManager from your application
  54. $em = GetMyEntityManager();
  55. $helperSet = new \Symfony\Component\Console\Helper\HelperSet(array(
  56. 'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()),
  57. 'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em)
  58. ));
  59. It is important to define a correct HelperSet that Doctrine binary
  60. script will ultimately use. The Doctrine Binary will automatically
  61. find the first instance of HelperSet in the global variable
  62. namespace and use this.
  63. .. note::
  64. You have to adjust this snippet for your specific application or framework
  65. and use their facilities to access the Doctrine EntityManager and
  66. Connection Resources.
  67. Command Overview
  68. ~~~~~~~~~~~~~~~~
  69. The following Commands are currently available:
  70. - ``help`` Displays help for a command (?)
  71. - ``list`` Lists commands
  72. - ``dbal:import`` Import SQL file(s) directly to Database.
  73. - ``dbal:run-sql`` Executes arbitrary SQL directly from the
  74. command line.
  75. - ``orm:clear-cache:metadata`` Clear all metadata cache of the
  76. various cache drivers.
  77. - ``orm:clear-cache:query`` Clear all query cache of the various
  78. cache drivers.
  79. - ``orm:clear-cache:result`` Clear result cache of the various
  80. cache drivers.
  81. - ``orm:convert-d1-schema`` Converts Doctrine 1.X schema into a
  82. Doctrine 2.X schema.
  83. - ``orm:convert-mapping`` Convert mapping information between
  84. supported formats.
  85. - ``orm:ensure-production-settings`` Verify that Doctrine is
  86. properly configured for a production environment.
  87. - ``orm:generate-entities`` Generate entity classes and method
  88. stubs from your mapping information.
  89. - ``orm:generate-proxies`` Generates proxy classes for entity
  90. classes.
  91. - ``orm:generate-repositories`` Generate repository classes from
  92. your mapping information.
  93. - ``orm:run-dql`` Executes arbitrary DQL directly from the command
  94. line.
  95. - ``orm:schema-tool:create`` Processes the schema and either
  96. create it directly on EntityManager Storage Connection or generate
  97. the SQL output.
  98. - ``orm:schema-tool:drop`` Processes the schema and either drop
  99. the database schema of EntityManager Storage Connection or generate
  100. the SQL output.
  101. - ``orm:schema-tool:update`` Processes the schema and either
  102. update the database schema of EntityManager Storage Connection or
  103. generate the SQL output.
  104. For these commands are also available aliases:
  105. - ``orm:convert:d1-schema`` is alias for ``orm:convert-d1-schema``.
  106. - ``orm:convert:mapping`` is alias for ``orm:convert-mapping``.
  107. - ``orm:generate:entities`` is alias for ``orm:generate-entities``.
  108. - ``orm:generate:proxies`` is alias for ``orm:generate-proxies``.
  109. - ``orm:generate:repositories`` is alias for ``orm:generate-repositories``.
  110. .. note::
  111. Console also supports auto completion, for example, instead of
  112. ``orm:clear-cache:query`` you can use just ``o:c:q``.
  113. Database Schema Generation
  114. --------------------------
  115. .. note::
  116. SchemaTool can do harm to your database. It will drop or alter
  117. tables, indexes, sequences and such. Please use this tool with
  118. caution in development and not on a production server. It is meant
  119. for helping you develop your Database Schema, but NOT with
  120. migrating schema from A to B in production. A safe approach would
  121. be generating the SQL on development server and saving it into SQL
  122. Migration files that are executed manually on the production
  123. server.
  124. SchemaTool assumes your Doctrine Project uses the given database on
  125. its own. Update and Drop commands will mess with other tables if
  126. they are not related to the current project that is using Doctrine.
  127. Please be careful!
  128. To generate your database schema from your Doctrine mapping files
  129. you can use the ``SchemaTool`` class or the ``schema-tool`` Console
  130. Command.
  131. When using the SchemaTool class directly, create your schema using
  132. the ``createSchema()`` method. First create an instance of the
  133. ``SchemaTool`` and pass it an instance of the ``EntityManager``
  134. that you want to use to create the schema. This method receives an
  135. array of ``ClassMetadataInfo`` instances.
  136. .. code-block:: php
  137. <?php
  138. $tool = new \Doctrine\ORM\Tools\SchemaTool($em);
  139. $classes = array(
  140. $em->getClassMetadata('Entities\User'),
  141. $em->getClassMetadata('Entities\Profile')
  142. );
  143. $tool->createSchema($classes);
  144. To drop the schema you can use the ``dropSchema()`` method.
  145. .. code-block:: php
  146. <?php
  147. $tool->dropSchema($classes);
  148. This drops all the tables that are currently used by your metadata
  149. model. When you are changing your metadata a lot during development
  150. you might want to drop the complete database instead of only the
  151. tables of the current model to clean up with orphaned tables.
  152. .. code-block:: php
  153. <?php
  154. $tool->dropSchema($classes, \Doctrine\ORM\Tools\SchemaTool::DROP_DATABASE);
  155. You can also use database introspection to update your schema
  156. easily with the ``updateSchema()`` method. It will compare your
  157. existing database schema to the passed array of
  158. ``ClassMetdataInfo`` instances.
  159. .. code-block:: php
  160. <?php
  161. $tool->updateSchema($classes);
  162. If you want to use this functionality from the command line you can
  163. use the ``schema-tool`` command.
  164. To create the schema use the ``create`` command:
  165. .. code-block:: php
  166. $ php doctrine orm:schema-tool:create
  167. To drop the schema use the ``drop`` command:
  168. .. code-block:: php
  169. $ php doctrine orm:schema-tool:drop
  170. If you want to drop and then recreate the schema then use both
  171. options:
  172. .. code-block:: php
  173. $ php doctrine orm:schema-tool:drop
  174. $ php doctrine orm:schema-tool:create
  175. As you would think, if you want to update your schema use the
  176. ``update`` command:
  177. .. code-block:: php
  178. $ php doctrine orm:schema-tool:update
  179. All of the above commands also accept a ``--dump-sql`` option that
  180. will output the SQL for the ran operation.
  181. .. code-block:: php
  182. $ php doctrine orm:schema-tool:create --dump-sql
  183. Before using the orm:schema-tool commands, remember to configure
  184. your cli-config.php properly.
  185. .. note::
  186. When using the Annotation Mapping Driver you have to either setup
  187. your autoloader in the cli-config.php correctly to find all the
  188. entities, or you can use the second argument of the
  189. ``EntityManagerHelper`` to specify all the paths of your entities
  190. (or mapping files), i.e.
  191. ``new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em, $mappingPaths);``
  192. Entity Generation
  193. -----------------
  194. Generate entity classes and method stubs from your mapping information.
  195. .. code-block:: php
  196. $ php doctrine orm:generate-entities
  197. $ php doctrine orm:generate-entities --update-entities
  198. $ php doctrine orm:generate-entities --regenerate-entities
  199. This command is not suited for constant usage. It is a little helper and does
  200. not support all the mapping edge cases very well. You still have to put work
  201. in your entities after using this command.
  202. It is possible to use the EntityGenerator on code that you have already written. It will
  203. not be lost. The EntityGenerator will only append new code to your
  204. file and will not delete the old code. However this approach may still be prone
  205. to error and we suggest you use code repositories such as GIT or SVN to make
  206. backups of your code.
  207. It makes sense to generate the entity code if you are using entities as Data
  208. Access Objects only and don't put much additional logic on them. If you are
  209. however putting much more logic on the entities you should refrain from using
  210. the entity-generator and code your entities manually.
  211. .. note::
  212. Even if you specified Inheritance options in your
  213. XML or YAML Mapping files the generator cannot generate the base and
  214. child classes for you correctly, because it doesn't know which
  215. class is supposed to extend which. You have to adjust the entity
  216. code manually for inheritance to work!
  217. Convert Mapping Information
  218. ---------------------------
  219. Convert mapping information between supported formats.
  220. This is an **execute one-time** command. It should not be necessary for
  221. you to call this method multiple times, especially when using the ``--from-database``
  222. flag.
  223. Converting an existing database schema into mapping files only solves about 70-80%
  224. of the necessary mapping information. Additionally the detection from an existing
  225. database cannot detect inverse associations, inheritance types,
  226. entities with foreign keys as primary keys and many of the
  227. semantical operations on associations such as cascade.
  228. .. note::
  229. There is no need to convert YAML or XML mapping files to annotations
  230. every time you make changes. All mapping drivers are first class citizens
  231. in Doctrine 2 and can be used as runtime mapping for the ORM. See the
  232. docs on XML and YAML Mapping for an example how to register this metadata
  233. drivers as primary mapping source.
  234. To convert some mapping information between the various supported
  235. formats you can use the ``ClassMetadataExporter`` to get exporter
  236. instances for the different formats:
  237. .. code-block:: php
  238. <?php
  239. $cme = new \Doctrine\ORM\Tools\Export\ClassMetadataExporter();
  240. Once you have a instance you can use it to get an exporter. For
  241. example, the yml exporter:
  242. .. code-block:: php
  243. <?php
  244. $exporter = $cme->getExporter('yml', '/path/to/export/yml');
  245. Now you can export some ``ClassMetadata`` instances:
  246. .. code-block:: php
  247. <?php
  248. $classes = array(
  249. $em->getClassMetadata('Entities\User'),
  250. $em->getClassMetadata('Entities\Profile')
  251. );
  252. $exporter->setMetadata($classes);
  253. $exporter->export();
  254. This functionality is also available from the command line to
  255. convert your loaded mapping information to another format. The
  256. ``orm:convert-mapping`` command accepts two arguments, the type to
  257. convert to and the path to generate it:
  258. .. code-block:: php
  259. $ php doctrine orm:convert-mapping xml /path/to/mapping-path-converted-to-xml
  260. Reverse Engineering
  261. -------------------
  262. You can use the ``DatabaseDriver`` to reverse engineer a database
  263. to an array of ``ClassMetadataInfo`` instances and generate YAML,
  264. XML, etc. from them.
  265. .. note::
  266. Reverse Engineering is a **one-time** process that can get you started with a project.
  267. Converting an existing database schema into mapping files only detects about 70-80%
  268. of the necessary mapping information. Additionally the detection from an existing
  269. database cannot detect inverse associations, inheritance types,
  270. entities with foreign keys as primary keys and many of the
  271. semantical operations on associations such as cascade.
  272. First you need to retrieve the metadata instances with the
  273. ``DatabaseDriver``:
  274. .. code-block:: php
  275. <?php
  276. $em->getConfiguration()->setMetadataDriverImpl(
  277. new \Doctrine\ORM\Mapping\Driver\DatabaseDriver(
  278. $em->getConnection()->getSchemaManager()
  279. )
  280. );
  281. $cmf = new DisconnectedClassMetadataFactory();
  282. $cmf->setEntityManager($em);
  283. $metadata = $cmf->getAllMetadata();
  284. Now you can get an exporter instance and export the loaded metadata
  285. to yml:
  286. .. code-block:: php
  287. <?php
  288. $exporter = $cme->getExporter('yml', '/path/to/export/yml');
  289. $exporter->setMetadata($metadata);
  290. $exporter->export();
  291. You can also reverse engineer a database using the
  292. ``orm:convert-mapping`` command:
  293. .. code-block:: php
  294. $ php doctrine orm:convert-mapping --from-database yml /path/to/mapping-path-converted-to-yml
  295. .. note::
  296. Reverse Engineering is not always working perfectly
  297. depending on special cases. It will only detect Many-To-One
  298. relations (even if they are One-To-One) and will try to create
  299. entities from Many-To-Many tables. It also has problems with naming
  300. of foreign keys that have multiple column names. Any Reverse
  301. Engineered Database-Schema needs considerable manual work to become
  302. a useful domain model.
  303. Runtime vs Development Mapping Validation
  304. -----------------------------------------
  305. For performance reasons Doctrine 2 has to skip some of the
  306. necessary validation of metadata mappings. You have to execute
  307. this validation in your development workflow to verify the
  308. associations are correctly defined.
  309. You can either use the Doctrine Command Line Tool:
  310. .. code-block:: php
  311. doctrine orm:validate-schema
  312. Or you can trigger the validation manually:
  313. .. code-block:: php
  314. <?php
  315. use Doctrine\ORM\Tools\SchemaValidator;
  316. $validator = new SchemaValidator($entityManager);
  317. $errors = $validator->validateMapping();
  318. if (count($errors) > 0) {
  319. // Lots of errors!
  320. echo implode("\n\n", $errors);
  321. }
  322. If the mapping is invalid the errors array contains a positive
  323. number of elements with error messages.
  324. .. warning::
  325. One mapping option that is not validated is the use of the referenced column name.
  326. It has to point to the equivalent primary key otherwise Doctrine will not work.
  327. .. note::
  328. One common error is to use a backlash in front of the
  329. fully-qualified class-name. Whenever a FQCN is represented inside a
  330. string (such as in your mapping definitions) you have to drop the
  331. prefix backslash. PHP does this with ``get_class()`` or Reflection
  332. methods for backwards compatibility reasons.
  333. Adding own commands
  334. -------------------
  335. You can also add your own commands on-top of the Doctrine supported
  336. tools if you are using a manually built console script.
  337. To include a new command on Doctrine Console, you need to do modify the
  338. ``doctrine.php`` file a little:
  339. .. code-block:: php
  340. <?php
  341. // doctrine.php
  342. use Symfony\Component\Console\Helper\Application;
  343. // as before ...
  344. // replace the ConsoleRunner::run() statement with:
  345. $cli = new Application('Doctrine Command Line Interface', \Doctrine\ORM\Version::VERSION);
  346. $cli->setCatchExceptions(true);
  347. $cli->setHelperSet($helperSet);
  348. // Register All Doctrine Commands
  349. ConsoleRunner::addCommands($cli);
  350. // Register your own command
  351. $cli->addCommand(new \MyProject\Tools\Console\Commands\MyCustomCommand);
  352. // Runs console application
  353. $cli->run();
  354. Additionally, include multiple commands (and overriding previously
  355. defined ones) is possible through the command:
  356. .. code-block:: php
  357. <?php
  358. $cli->addCommands(array(
  359. new \MyProject\Tools\Console\Commands\MyCustomCommand(),
  360. new \MyProject\Tools\Console\Commands\SomethingCommand(),
  361. new \MyProject\Tools\Console\Commands\AnotherCommand(),
  362. new \MyProject\Tools\Console\Commands\OneMoreCommand(),
  363. ));