Week 12, year 2011
- Accessing private properties from other instances - In PHP, when a property or method is marked private, it can only be accessed from within that class. That includes other instances of the same class. This may seem counter-intuitive at first, because we are used to dealing with instances of classes. The visibility operator however works not on object-level, but on class level. An example: <?phpclassFoo{private$private;publicfunction__construct($value){$this->private=$value;}publicfunctiongetOther(Foo$object){return$object->private;}}$foo1=newFoo('foo1');$foo2=newFoo('foo2');echo$foo1->getOther($foo2);// outputs 'foo2' This should make it clear that both instances of Foo have access to each other’s private properties. What practical use does this have? A great candidate for this are Value Objects. [Mathias Verraes]
- Keep your controllers thin with Doctrine2 - Doctrine2 does such a nice job abstracting everything related to the database, that you might be tempted to do everything else in your controllers. Say we have a Bug entity: <?php/** @Entity */classBug{/** @Column(type="integer") */private$id;/** @Column(length=50) */private$status;//. . . } To get a list of fixed bugs, we get the Bug repository from the EntityManager and ask for a list of Bugs where status equals ‘fixed’. <?php<?php// $em instanceof Doctrine\ORM\EntityManager$fixedbugs=$em->getRepository('Bug')->findBy(array('status'=>'fixed')); That’s easy enough. [Mathias Verraes]