forked from Ocramius/Doctrine2ORMSlidesTutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1169 lines (1076 loc) · 39 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Doctrine 2 ORM Tutorial</title>
<!-- jQuery + jQuery history -->
<script type="text/javascript" src="vendor/slippy/src/jquery.min.js"></script>
<script type="text/javascript" src="vendor/slippy/src/jquery.history.js"></script>
<!-- Slippy -->
<script type="text/javascript" src="vendor/slippy/src/slippy.js"></script>
<link type="text/css" rel="stylesheet" href="vendor/slippy/src/slippy.css"/>
<link type="text/css" rel="stylesheet" href="vendor/slippy/src/slippy-pure.css"/>
<!-- Syntax highlighting core and style -->
<script type="text/javascript" src="vendor/syntax-highlighter/scripts/XRegExp.js"></script>
<script type="text/javascript" src="vendor/syntax-highlighter/scripts/shCore.js"></script>
<!--<script type="text/javascript" src="vendor/syntax-highlighter/scripts/shAutoloader.js"></script>-->
<link type="text/css" rel="stylesheet" href="vendor/syntax-highlighter/styles/shCore.css"/>
<link type="text/css" rel="stylesheet" href="vendor/syntax-highlighter/styles/shCoreMDUltra.css"/>
<!-- Highlighter brushes (php, bash) -->
<script type="text/javascript" src="vendor/syntax-highlighter/scripts/shBrushPhp.js"></script>
<script type="text/javascript" src="vendor/syntax-highlighter/scripts/shBrushBash.js"></script>
<script type="text/javascript">
/*SyntaxHighlighter.autoloader(
'applescript vendor/syntax-highlighter/scripts/shBrushAppleScript.js',
'actionscript3 as3 vendor/syntax-highlighter/scripts/shBrushAS3.js',
'bash shell vendor/syntax-highlighter/scripts/shBrushBash.js',
'coldfusion cf vendor/syntax-highlighter/scripts/shBrushColdFusion.js',
'cpp c vendor/syntax-highlighter/scripts/shBrushCpp.js',
'c# c-sharp csharp vendor/syntax-highlighter/scripts/shBrushCSharp.js',
'css vendor/syntax-highlighter/scripts/shBrushCss.js',
'delphi pascal vendor/syntax-highlighter/scripts/shBrushDelphi.js',
'diff patch pas vendor/syntax-highlighter/scripts/shBrushDiff.js',
'erl erlang vendor/syntax-highlighter/scripts/shBrushErlang.js',
'groovy vendor/syntax-highlighter/scripts/shBrushGroovy.js',
'java vendor/syntax-highlighter/scripts/shBrushJava.js',
'jfx javafx vendor/syntax-highlighter/scripts/shBrushJavaFX.js',
'js jscript javascript vendor/syntax-highlighter/scripts/shBrushJScript.js',
'perl pl vendor/syntax-highlighter/scripts/shBrushPerl.js',
'php vendor/syntax-highlighter/scripts/shBrushPhp.js',
'text plain vendor/syntax-highlighter/scripts/shBrushPlain.js',
'py python vendor/syntax-highlighter/scripts/shBrushPython.js',
'ruby rails ror rb vendor/syntax-highlighter/scripts/shBrushRuby.js',
'scala vendor/syntax-highlighter/scripts/shBrushScala.js',
'sql vendor/syntax-highlighter/scripts/shBrushSql.js',
'vb vbnet vendor/syntax-highlighter/scripts/shBrushVb.js',
'xml xhtml xslt html vendor/syntax-highlighter/scripts/shBrushXml.js'
);*/
$(function() {
$(".slide").slippy({});
SyntaxHighlighter.defaults['toolbar'] = false;
SyntaxHighlighter.all();
});
</script>
<!-- Custom styling -->
<link type="text/css" rel="stylesheet" href="style/slippy-styled.css"/>
</head>
<body>
<div class="slide" style="text-align: center;">
<h1>Doctrine 2 ORM</h1>
<h3>Object Relational Mapper for PHP 5.3</h3>
<p style="padding-top: 20px;">
<img src="image/common_icon.png" alt="Doctrine"/>
</p>
</div>
<div class="slide">
<h2>Some history of RDBMS persistence in PHP:</h2>
<ol>
<li>mysql_query, mysql_fetch_array, mysql_*</li>
<li>mysqli, PDO</li>
<li>Doctrine 1.2, Propel 1.6, Zend_Db</li>
</ol>
</div>
<div class="slide">
<h2>mysql_query</h2>
</div>
<div class="slide">
<pre class="brush: php">
mysql_connect('localhost', 'user', 'password');
mysql_select_db('test');
//simple example
mysql_query('INSERT INTO greetings (content) VALUES ("' . mysql_real_escape_string($_POST['greeting']) . '")');
//comments example
mysql_query('INSERT INTO users (username) VALUES ("' . mysql_real_escape_string($_POST['username']) . '")');
mysql_query('INSERT INTO comments (user_id, content) VALUES (' . mysql_insert_id() . ', "' . mysql_real_escape_string($_POST['content']) . '")');
</pre>
</div>
<div class="slide">
<h3>mysql_query</h3>
<ul>
<li class="cons">
We had to write our queries and our security (mysql_real_escape_string()) by ourselves.
</li>
<li class="cons">
Also, we had to keep track of identifiers of the inserted fields by ourselves.
</li>
<li class="cons">
We had to rewrite every function name (and probably also functionality) when switching database vendor.
</li>
<li class="cons">
Not really OO friendly, heh?
</li>
</ul>
</div>
<div class="slide">
<h2>PDO</h2>
</div>
<div class="slide">
<pre class="brush: php">
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
//simple example
$sth = $dbh->prepare('INSERT INTO greetings (content) VALUES (:content);
$sth->execute(array(':content' => $_POST['content']));
//comments example
$sth = $dbh->prepare('INSERT INTO users (username) VALUES (:username)');
$sth->execute(array(':username' => $_POST['username']));
$sth = $dbh->prepare('INSERT INTO comments (user_id, content) VALUES (user_id, :content)');
$sth->execute(array(':user_id' => $dbh->lastInsertId(), ':content' => $_POST['content']);
} catch (PDOException $e) {
echo $e->getMessage();
}
</pre>
</div>
<div class="slide">
<h3>PDO</h3>
<ul>
<li class="pro">
We now can connect to different databases. MySQL is no more the only option!
</li>
<li class="pro">
Security is given by named parameters, escaped for us by PDO!
</li>
<li class="pro">
Prepared statements make our queries easier to reuse!
</li>
<li class="pro">
Exceptions are used, we can now catch them!
</li>
<li class="cons">
Queries are still performed in the SQL dialect of the vendor, which could make our code not 100% portable.
</li>
<li class="cons">
Still have to keep track of identifiers of the inserted fields by ourselves.
</li>
</ul>
</div>
<div class="slide">
<h2>Doctrine 1.2</h2>
<p>An Active Record implementation</p>
</div>
<div class="slide">
<h3>Greeting record definition</h3>
<pre class="brush: php">
class Greeting extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('greetings');
$this->hasColumn(
'content',
'string',
255,
array(
'type' => 'string',
'length' => '255'
)
);
}
}
</pre>
</div>
<div class="slide">
<pre class="brush: php">
//simple example
$greeting = new Greeting();
$greeting->content = $_POST['content'];
$greeting->save();
</pre>
</div>
<div class="slide">
<h3>User record definition</h3>
<pre class="brush: php">
class User extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('users');
$this->hasColumn(
'username',
'string',
255,
array(
'type' => 'text',
)
);
}
public function setUp()
{
$this->hasMany(
'Comments as Comments',
array(
'refClass' => 'Comment',
'local' => 'id',
'foreign' => 'user_id'
)
);
}
}
</pre>
</div>
<div class="slide">
<h3>Person record definition</h3>
<pre class="brush: php">
class Comment extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('comments');
$this->hasColumn(
'content',
'string',
255,
array(
'type' => 'string',
'length' => '255'
)
);
$this->hasColumn(
'user_id',
'string',
255,
array(
'type' => 'integer',
)
);
}
public function setUp()
{
$this->hasOne(
'User',
array(
'refClass' => 'User',
'local' => 'user_id',
'foreign' => 'id'
)
);
}
}
</pre>
</div>
<div class="slide">
<pre class="brush: php">
//comments example
$user = new User();
$user->username = $_POST['username'];
$comment = new Comment();
$comment->content = $_POST['content'];
$user->Comments[] = $comment;
$comment->User = $user;
$user->save();
</pre>
</div>
<div class="slide">
<h3>Doctrine 1.2</h3>
<ul>
<li class="pro">
Objects are written to DB by Doctrine: no more SQL!
</li>
<li class="pro">
Associations are managed by Doctrine: no more foreign key mess!
</li>
<li class="pro">
Object-Oriented approach!
</li>
<li class="pro">
Database is abstracted by a powerful DBAL layer: no more SQL portability troubles!
</li>
<li class="pro">
Database can be generated by our models!
</li>
<li class="cons">
Table definition is set in our domain logic.
</li>
<li class="cons">
A lot of PHP "magic" is happening (__set, __get, etc.).
</li>
<li class="cons">
Our objects must extend Doctrine_Record to be used with Doctrine
</li>
</ul>
</div>
<div class="slide">
<h2>Doctrine 2</h2>
</div>
<div class="slide">
<h3>What is Doctrine 2?</h3>
<ul>
<li class="pro">
Doctrine 2 is a Data Mapper implementation:
<br/>
<img src="image/databaseMapperSketch.gif" alt="Data Mapper" style="width: 60%; margin: 10px;"/>
</li>
<li class="pro">
Used the well known Java Persistence API (JPA, aka JSR 317) as initial blueprint
</li>
<li class="pro">
It separates persistence and domain logic. You are now able to port your logic to SQL, NoSQL, XML mappers, etc.
</li>
<li class="pro">
It provides around 3X better performance than Doctrine 1.2.
</li>
<li class="pro">
Your objects won't need to extend anything.
</li>
<li class="pro">
You are free to save anything you want to your database, just map it!
</li>
<li class="pro">
You can even map existing classes to database tables!
</li>
</ul>
</div>
<div class="slide">
<h2>Doctrine 2 Requirements</h2>
<ul>
<li>
PHP 5.3
</li>
<li>
Doctrine\Common (bundled)
<br/>
  A set of utilities common to all Doctrine projects
</li>
<li>
Doctrine\DBAL (bundled)
<br/>
  A very powerful Database ABstraction Layer
</li>
<li>
Symfony\Component\Console (bundled)
<br/>
  A CLI runner tool
</li>
<li>
Symfony\Component\Yaml (bundled)
<br/>
  If you work with YAML configuration
</li>
</ul>
</div>
<div class="slide">
<h2>Getting started</h2>
<pre class="brush: bash">
mkdir doctrine-demo
cd doctrine-demo
mkdir library
mkdir library/Entity
touch library/Entity/Greeting.php
mkdir library/EntityProxy
chmod +w library/EntityProxy
echo "{}" > composer.json
curl -s https://getcomposer.org/installer | php
./composer.phar require doctrine/orm:2.*
touch bootstrap.php
</pre>
</div>
<div class="slide">
<h2>Create entities...</h2>
</div>
<div class="slide">
<pre class="brush: php">
namespace Entity;
class Greeting
{
/** @var int */
private $id;
/** @var string */
private $content;
}
</pre>
</div>
<div class="slide">
<h2>...add getters, setters, constructors, other methods...</h2>
</div>
<div class="slide">
<pre class="brush: php, highlight: [12, 19, 26, 33];">
namespace Entity;
class Greeting
{
/** @var int */
private $id;
/** @var string */
private $content;
public function __construct($content) {
$this->setContent($content);
}
/**
* @return int
*/
public function getId() {
return $this->id;
}
/**
* @return string
*/
public function getContent() {
return $this->content;
}
/**
* @param string $content
*/
public function setContent($content) {
$this->content = (string) $content;
}
}
</pre>
</div>
<div class="slide">
<h2>...add mappings (@Annotations) to entities...</h2>
</div>
<div class="slide">
<pre class="brush: php, highlight: [3, 6, 12, 13, 14, 20];">
namespace Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Greeting
{
/**
* @ORM\Id()
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
* @var int
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
* @var string
*/
private $content;
public function __construct($content) {
$this->setContent($content);
}
/**
* @return int
*/
public function getId() {
return $this->id;
}
/**
* @return string
*/
public function getContent() {
return $this->content;
}
/**
* @param string $content
*/
public function setContent($content) {
$this->content = (string) $content;
}
}
</pre>
</div>
<div class="slide">
<h2>Creating an EntityManager</h2>
</div>
<div class="slide">
<h3>Autoloading:</h3>
<pre class="brush: php">
<?php
// bootstrap.php
use Doctrine\ORM\Tools\Setup,
Doctrine\ORM\EntityManager,
Doctrine\ORM\Configuration,
Doctrine\Common\Cache\ArrayCache as Cache,
Doctrine\Common\Annotations\AnnotationRegistry,
Doctrine\Common\ClassLoader;
//autoloading
require_once __DIR__ . '/vendor/autoload.php';
$loader = new ClassLoader('Entity', __DIR__ . '/library');
$loader->register();
$loader = new ClassLoader('EntityProxy', __DIR__ . '/library');
$loader->register();
</pre>
</div>
<div class="slide">
<h3>Configuration and metadata</h3>
<pre class="brush: php">
//configuration
$config = new Configuration();
$cache = new Cache();
$config->setQueryCacheImpl($cache);
$config->setProxyDir(__DIR__ . '/library/EntityProxy');
$config->setProxyNamespace('EntityProxy');
$config->setAutoGenerateProxyClasses(true);
//mapping (example uses annotations, could be any of XML/YAML or plain PHP)
AnnotationRegistry::registerFile(__DIR__ . '/library/doctrine-orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php');
$driver = new Doctrine\ORM\Mapping\Driver\AnnotationDriver(
new Doctrine\Common\Annotations\AnnotationReader(),
array(__DIR__ . '/library/Entity')
);
$config->setMetadataDriverImpl($driver);
$config->setMetadataCacheImpl($cache);
</pre>
</div>
<div class="slide">
<h3>Creating the EntityManager</h3>
<pre class="brush: php">
//getting the EntityManager
$em = EntityManager::create(
array(
'driver' => 'pdo_sqlite',
'path' => 'database.sqlite'
),
$config
);
</pre>
</div>
<div class="slide">
<h3>Final result:</h3>
<pre class="brush: php">
<?php
// bootstrap.php
use Doctrine\ORM\Tools\Setup,
Doctrine\ORM\EntityManager,
Doctrine\ORM\Configuration,
Doctrine\Common\Cache\ArrayCache as Cache,
Doctrine\Common\Annotations\AnnotationRegistry,
Doctrine\Common\ClassLoader;
//autoloading
require_once __DIR__ . '/vendor/autoload.php';
$loader = new ClassLoader('Entity', __DIR__ . '/library');
$loader->register();
$loader = new ClassLoader('EntityProxy', __DIR__ . '/library');
$loader->register();
//configuration
$config = new Configuration();
$cache = new Cache();
$config->setQueryCacheImpl($cache);
$config->setProxyDir(__DIR__ . '/library/EntityProxy');
$config->setProxyNamespace('EntityProxy');
$config->setAutoGenerateProxyClasses(true);
//mapping (example uses annotations, could be any of XML/YAML or plain PHP)
AnnotationRegistry::registerFile(__DIR__ . '/library/doctrine-orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php');
$driver = new Doctrine\ORM\Mapping\Driver\AnnotationDriver(
new Doctrine\Common\Annotations\AnnotationReader(),
array(__DIR__ . '/library/Entity')
);
$config->setMetadataDriverImpl($driver);
$config->setMetadataCacheImpl($cache);
//getting the EntityManager
$em = EntityManager::create(
array(
'driver' => 'pdo_sqlite',
'path' => 'database.sqlite'
),
$config
);
</pre>
</div>
<div class="slide">
<h2>Generating the schema</h2>
<h3>(Configuring doctrine-cli.php)</h3>
</div>
<div class="slide">
<h3>CLI runner</h3>
<pre class="brush: php">
<?php
//doctrine-cli.php
use Symfony\Component\Console\Helper\HelperSet,
Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper,
Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper,
Doctrine\ORM\Tools\Console\ConsoleRunner;
require_once __DIR__ . '/bootstrap.php';
$helperSet = new HelperSet(array(
'em' => new EntityManagerHelper($em),
'conn' => new ConnectionHelper($em->getConnection())
));
ConsoleRunner::run($helperSet);
</pre>
</div>
<div class="slide">
<h3>Generating the schema</h3>
<pre class="brush: bash, highlight: [5];">
$ php doctrine-cli.php orm:schema-tool:create
ATTENTION: This operation should not be executed in a production environment.
Creating database schema...
Database schema created successfully!
</pre>
</div>
<div class="slide">
<p>Generated database as seen by SQLite browser</p>
<img src="image/database-status.png" alt="Generated Database"/>
</div>
<div class="slide">
<h2>Working with the EntityManager</h2>
</div>
<div class="slide">
<h3>Saving a "Entity\Greeting" object</h3>
<pre class="brush: php, highlight: [11, 14];">
//examples/1.php
use Entity\Greeting;
require_once __DIR__ . '/../bootstrap.php';
//Creating our greeting
$greeting = new Greeting('Hello World!');
//Registering $greeting with the EntityManager
$em->persist($greeting);
//Flushing all changes to database
$em->flush();
echo 'OK!';
</pre>
</div>
<div class="slide">
<h3>Retrieving an "Entity\Greeting" object</h3>
<pre class="brush: php, highlight: [5, 9, 10];">
//examples/2.php
require_once __DIR__ . '/../bootstrap.php';
//Finding Greeting with id = 1
$greeting = $em->find('Entity\Greeting', 1);
if($greeting) {
//The EntityManager has already provided us an object of type Entity\Greeting!
echo 'Found a greeting (instance of ' . get_class($greeting)
. ') with content ' . $greeting->getContent();
}else{
echo 'Couldn\'t find Greeting with id=1';
}
</pre>
</div>
<div class="slide">
<h3>Updating an "Entity\Greeting" object</h3>
<pre class="brush: php, highlight: [5, 11, 13];">
//examples/3.php
require_once __DIR__ . '/../bootstrap.php';
//Finding Greeting with id = 1
$greeting = $em->find('Entity\Greeting', 1);
if($greeting) {
echo $greeting->getContent() . PHP_EOL;
echo 'Changing the contents of found Greeting to "Hello Test!"' . PHP_EOL;
//Using Entity\Greeting to set a new content for the $greeting!
$greeting->setContent('Hello Test!');
//Flushing changes to database (triggers SQL updates)
$em->flush();
echo 'Now try loading 2.php again!' . PHP_EOL;
}else{
echo 'Couldn\'t find Greeting with id=1';
}
</pre>
</div>
<div class="slide">
<h3>Finding "Entity\Greeting" objects</h3>
<pre class="brush: php, highlight: [5, 8, 11, 15, 20];">
//examples/4.php
require_once __DIR__ . '/../bootstrap.php';
//A repository is like a "Table" containing our entities of a specified type
$repository = $em->getRepository('Entity\Greeting');
//Finding all Entity\Greeting with content = "Hello World!"
$worldGreetings = $repository->findBy(array('content' => 'Hello World!'));
//Finding all Entity\Greeting with content = "Hello Test!"
$testGreetings = $repository->findBy(array('content' => 'Hello Test!'));
//Displaying results
echo 'Found ' . count($worldGreetings) . ' "Hello World!" greetings:' . PHP_EOL;
foreach($worldGreetings as $worldGreeting) {
echo ' - ' . $worldGreeting->getId() . PHP_EOL;
}
echo 'Found ' . count($testGreetings) . ' "Hello Test!" greetings:' . PHP_EOL;
foreach($testGreetings as $testGreeting) {
echo ' - ' . $testGreeting->getId() . PHP_EOL;
}
</pre>
</div>
<div class="slide">
<h3>Retrieving "Entity\Greeting" objects via DQL</h3>
<pre class="brush: php, highlight: [6, 11];">
//examples/5.php
require_once __DIR__ . '/../bootstrap.php';
//Creating a DQL query that selects all greetings with id >= 5 and id <= 10
$greetings = $em
->createQuery('SELECT g FROM Entity\Greeting g WHERE g.id >= 5 AND g.id <= 10')
->getResult();
//Displaying results
echo 'Found ' . count($greetings) . ' Entity\Greeting:' . PHP_EOL;
foreach($greetings as $greeting) {
echo ' - ' . $greeting->getId() . ' => ' . $greeting->getContent() . PHP_EOL;
}
</pre>
</div>
<div class="slide">
<h3>Deleting "Entity\Greeting" objects</h3>
<pre class="brush: php, highlight: [6, 7, 14, 16];">
//examples/6.php
require_once __DIR__ . '/../bootstrap.php';
//Finding the last inserted greeting
$greetings = $em
->createQuery('SELECT g FROM Entity\Greeting g ORDER BY g.id DESC')
->setMaxResults(1) //we want only one result
->getResult();
if(!empty($greetings)) {
$greeting = reset($greetings);
echo 'Found greeting with id "' . $greeting->getId()
. '" and content "' . $greeting->getContent() . '"' . PHP_EOL;
$em->remove($greeting);
//Triggers delete
$em->flush();
echo 'Greeting deleted!' . PHP_EOL;
} else {
echo 'Could not find any Greeting' . PHP_EOL;
}
</pre>
</div>
<div class="slide">
<h2>Working with associations</h2>
</div>
<div class="slide">
<h3>You will need additional code:</h3>
<ul>
<li>Entity\Post</li>
<li>Entity\Comment</li>
</ul>
</div>
<div class="slide">
<h3>We don't define IDs, we define how objects are related:</h3>
<p>
<strong>ONE</strong> Entity\Post
<br/>
  <strong>HAS MANY</strong> Entity\Comment
</p>
<p>
<strong>ONE</strong> Entity\Comment
<br/>
  <strong>HAS ONE</strong> Entity\Post
</p>
</div>
<div class="slide">
<h3>In Doctrine terms:</h3>
<p>
Entity\Post::comments
<br/>
   is a <strong>OneToMany</strong> relation to <strong>Entity\Comment</strong>, <strong>mapped by</strong> Entity\Comment#post
</p>
<p>
Entity\Comment::post
<br/>
   is a <strong>ManyToOne</strong> relation to <strong>Entity\Post</strong>, <strong>inversed by</strong> Entity\Post#comments
</p>
</div>
<div class="slide">
<h3>Available relations:</h3>
<ul>
<li>
OneToMany (mapped by ManyToOne)
</li>
<li>
ManyToOne (inversed by OneToMany)
</li>
<li>
OneToOne (inversed/mapped by OneToOne)
</li>
<li>
ManyToMany (inversed/mapped by ManyToMany)
</li>
</ul>
<p>
OneToMany and ManyToMany relations are represented in Doctrine by instances of the Doctrine\Common\Collections\Collection interface.
</p>
</div>
<div class="slide">
<h3>Relations ownership</h3>
<p>
Relationship between entities may be <strong>inversed (bidirectional)</strong> or <strong>unidirectional</strong>.
</p>
</div>
<div class="slide">
<p>
There is always an <strong>owning side</strong> of the relation.
</p>
<p>
A bidirectional relationship has both an <strong>owning side</strong> and an <strong>inverse side</strong>.
</p>
<p>
A unidirectional relationship has only an <strong>owning side</strong>.
</p>
<p>
The <strong>owning side</strong> of the relation <strong>is the one checked by Doctrine</strong> to determine changes to the relation graph.
</p>
</div>
<div class="slide">
<p>
Some rules apply to relations, you can read them at
<br/>
<a href="http://www.doctrine-project.org/docs/orm/2.0/en/reference/association-mapping.html" target="_blank">
http://www.doctrine-project.org/docs/orm/2.0/en/reference/association-mapping.html
</a>
</p>
<p>
<strong>Please be sure to have read them before getting to work with Doctrine.</strong>
</p>
</div>
<div class="slide">
<h2>Using associations</h2>
<h3>We will map some entities to check how associations work...</h3>
</div>
<div class="slide">
<pre class="brush: php, highlight: [12, 13, 18, 19, 25, 32];">
/** @ORM\Entity */
class User
{
/** @ORM\Id() @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") @var int */
private $id;
/** @ORM\Column(type="string", length=255) @var string */
private $login;
/**
* @ORM\OneToMany(targetEntity="Entity\Comment", mappedBy="user")
* @var Collection
*/
private $comments;
public function __construct($login) {
//Initializing collection. Doctrine recognizes Collections, not arrays!
$this->comments = new ArrayCollection();
$this->setLogin($login);
}
//Getters and setters
/** @return Collection */
public function getComments() {
return $this->comments;
}
/** @param Comment $comment */
public function addComment(Comment $comment) {
$this->comments->add($comment);
$comment->setUser($this);
}
}
</pre>
</div>
<div class="slide">
<pre class="brush: php, highlight: [12, 13, 23, 28];">
/** @ORM\Entity */
class Comment
{
/** @ORM\Id() @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") @var int */
private $id;
/** @ORM\Column(type="string", length=255) @var string */
private $content;
/**
* @ORM\ManyToOne(targetEntity="Entity\User", inversedBy="comments")
* @var User|null
*/
private $user;
public function __construct($content) {
$this->setContent($content);
}
//Setters, getters
/** @return User|null */
public function getUser() {
return $this->user;
}
/** @param User $user */
public function setUser(User $user) {
if($user === null || $user instanceof User) {
$this->user = $user;
} else {
throw new InvalidArgumentException('$user must be instance of Entity\User or null!');
}
}
}
</pre>
</div>
<div class="slide">
<h2>Now to the examples</h2>
</div>
<div class="slide">
<h3>Creating a User with a related Comment</h3>
<pre class="brush: php, highlight: [8, 9, 11, 12, 14, 17];">
//examples/7.php
use Entity\User,
Entity\Comment;
require_once __DIR__ . '/../bootstrap.php';
//Creating our user
$user = new User('Marco Pivetta');
$em->persist($user);
$comment = new Comment('This is a sample post!');
$em->persist($comment);
$user->addComment($comment);
//Flushing all changes to database
$em->flush();
echo 'OK!';
</pre>
</div>
<div class="slide">
<h3>Fetching the User and it's related Comment</h3>
<pre class="brush: php, highlight: [5, 11, 12, 13];">
//examples/8.php
require_once __DIR__ . '/../bootstrap.php';
//Finding previously persisted user
$user = $em->find('Entity\User', 1);
if($user) {
echo 'Found an Entity\User: ' . PHP_EOL
. $user->getId() . ' => ' . $user->getLogin() . '(' . get_class($user) . ')' . PHP_EOL
. 'and ' . $user->getComments()->count() . ' Entity\Comment attached to it: ' . PHP_EOL;
foreach($user->getComments() as $comment) {
echo ' ' . $comment->getId() . ' => ' . $comment->getContent()
. ' (' . get_class($comment) . ')' . PHP_EOL;
}
} else {
echo 'Could not find Entity\User with id=1';
}
</pre>
</div>
<div class="slide">
<h3>Attaching a Comment to an existing User</h3>
<pre class="brush: php, highlight: [7, 14, 15, 16, 17];">
//examples/9.php