In this talk I gave at the Symfony User Group Hamburg, I describe how I built a reusable Symfony2 Bundle that allows the user to add tags to any Entity without having to copy & paste source code.
2. Anti-Pattern #1
Reusage by copy & paste
Every time
you do this,
a baby seal
dies
Photo by Samuel Blanc via Wikimedia Commons
[CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0)]
4. I can haz tagz?
Illustration by Kimhunghan via Wikimedia Commons
[CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0)]
Backend
• fpn/tag-bundle
Frontend
• max-favilli/tagmanager
+ something in between
5. fpn/tag-bundle
Actually a Doctrine Extension in a Bundle
Pro
•Provides two new Entites: Tag & Tagging
•TagManager handles model access
Con
•Some code to copy into our Entities
•Lots of code to copy into our Controllers
8. Form Widget
Two input fields
• visible for UI
• hidden for „tagA, tagB, tagC“
Embed JavaScript & CSS
Initialize JS
9. Data Transformer
transform()
• convert Tags to „a, b, c“
reverseTransform()
• convert „tagA, tagB, tagC“ to Tags
• create Tags, if not existing
• needs TagManager
10. Form Type
Provide name for widget
Called in Application FormTypes
Gets TagManager injected
Defines DataTransformer
11. Save the baby seals
Entity Trait
TaggableSubstriber
make it reusable
12. Entity Trait
avoid copy & paste for each
functional Entity classes
reference TagManager
• after loading the Entity
• to inform TagManager during flush
Willkommen Fragen, Anmerkungen, Meinungen Vorstellung seit 2001 Software & Betrieb Fauler Entwickler Wiederverwendung Hürden Technologie Lizenz Umsetzung
Patterns Anti-Patterns Warum nicht? Robbenbaby
Text-Input? Pre-filled list / checkboxes Tags Suche bei Google, KnpBundles „Tag“ + „Symfony2“ ist vergiftet (DependencyInjection) Wo noch suchen?
Eindeutigkeit der Bezeichner
FormTypes als Service Erlaubt Injection vom TagManager
Code in Entity überflüssig machen Controller soll Entity nach Tags befragen Besser: Event werfen, wenn Entity dirty ist..
JS/CSS files sind nicht teil meines Projekts Composer kümmert sich um Aktualisierung