Successfully reported this slideshow.
Your SlideShare is downloading. ×

How I started to love design patterns

Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Upcoming SlideShare
Présentation Docker
Présentation Docker
Loading in …3
×

Check these out next

1 of 44 Ad

How I started to love design patterns

Download to read offline

Il arrive parfois que nous, développeurs, pensions qu’il n’est pas nécessaire de connaître ce qu’ils appellent les « design patterns » ou « patrons de conception ». Nous pensons parfois que nous n’avons pas besoin de cette théorie. Après des années d’expériences avec la faible maintenabilité de mon propre code et de celui de mes clients, j’ai exploré de nombreuses façons de découpler nos applications afin de créer des applications « enterprise ready » qui peuvent vivre pendant de nombreuses années. Via des exemples concrets, je vais vous présenter quelques design patterns qui peuvent vous aider à travailler sur une codebase propre, structurée et bien découplée.

Il arrive parfois que nous, développeurs, pensions qu’il n’est pas nécessaire de connaître ce qu’ils appellent les « design patterns » ou « patrons de conception ». Nous pensons parfois que nous n’avons pas besoin de cette théorie. Après des années d’expériences avec la faible maintenabilité de mon propre code et de celui de mes clients, j’ai exploré de nombreuses façons de découpler nos applications afin de créer des applications « enterprise ready » qui peuvent vivre pendant de nombreuses années. Via des exemples concrets, je vais vous présenter quelques design patterns qui peuvent vous aider à travailler sur une codebase propre, structurée et bien découplée.

Advertisement
Advertisement

More Related Content

Slideshows for you (20)

Similar to How I started to love design patterns (20)

Advertisement

Recently uploaded (20)

Advertisement

How I started to love design patterns

  1. 1. How I started to love what they call Design Patterns @samuelroze
  2. 2. Samuel Rozé VP of Engineering @ Birdie Symfony ContinuousPipe Tolerance
  3. 3. I started years ago...
  4. 4. I probably wrote that <?php include 'header.php'; include 'pages/'. $_GET['page'].'.php'; include 'footer.php';
  5. 5. At some point I used Symfony class EntityController extends AbstractController { public function action( EntityManagerInterface $entityManager, string $identifier ) { $entity = $entityManager->getRepository(Entity::class) ->find($identifier); return $this->render('my-template.html.twig', [ 'entity' => $entity, ]); } }
  6. 6. Then I updated my entity... public function action( EntityManagerInterface $entityManager, Request $request, string $identifier ) { // ... if ($request->isMethod('POST')) { $form->handleRequest($request); if ($form->isValid()) { $entity = $form->getData(); $entityManager->persist($entity); $entityManager->flush(); } } // ... }
  7. 7. Then I sent an email // ... if ($form->isValid()) { $entity = $form->getData(); $entityManager->persist($entity); $entityManager->flush(); $mailer->send( (new Email()) ->setTo('samuel.roze@gmail.com') ->setBody('Very long text here...') ->setFrom('My super application') // ... ); } // ...
  8. 8. Well... that's long! class EntityController extends AbstractController { public function action( EntityManagerInterface $entityManager, MailerInterface $mailer, Request $request, string $identifier ) { $entity = $entityManager->getRepository(Entity::class) ->find($identifier); $form = $this->createForm(EntityFormType::class, $entity); if ($request->isMethod('POST')) { $form->handleRequest($request); if ($form->isValid()) { $entity = $form->getData(); $entityManager->persist($entity); $entityManager->flush(); $mailer->send( (new Email()) ->setTo('samuel.roze@gmail.com') ->setBody('Very long text here...') ->setFrom('My super application') ); } } return $this->render('my-template.html.twig', [ 'entity' => $entity, ]); } }
  9. 9. And then... It became un-maintanable
  10. 10. Design Patterns
  11. 11. A general reusable solution to a commonly occurring problem within a given context. 1 Wikipedia
  12. 12. All the design patterns do the same thing: control the information flow. 1 Anthony Ferrara
  13. 13. Let's do some refactoring!
  14. 14. Why do we refactor? 4 We want to reuse code 4 So we delegate the responsibilities 4 And improve the readability 4 And therefore we ensure maintainability 4 By doing so we enable change
  15. 15. Adapter
  16. 16. Adapter interface EntityRepository { public function find(string $identifier): ?Entity; public function save(Entity $entity): Entity; }
  17. 17. Adapter final class DoctrineEntityRepository implements EntityRepository { private $entityManager; public function __construct(EntityManagerInterface $entityManager) { $this->entityManager = $entityManager; } public function find(string $identifier) : ?Entity { return $this->entityManager->getRepository(Entity::class) ->find($identifier); } // ... }
  18. 18. Adapter final class DoctrineEntityRepository implements EntityRepository { // ... public function save(Entity $entity) : Entity { $entity = $this->entityManager->merge($entity); $this->entityManager->persist($entity); $this->entityManager->flush(); return $entity; } }
  19. 19. class EntityController extends AbstractController { public function action( EntityRepository $entityRepository, Request $request, string $identifier ) { $entity = $entityRepository->find($identifier); // ... if ($form->isValid()) { $entityRepository->save($entity); $mailer->send( (new Email())->setBody('Hey, something was updated!') ); } } }
  20. 20. class EntityController { public function __construct(EntityRepository $entityRepository, /** ... **/) { /** ... **/ } public function action(Request $request, string $identifier) { $entity = $this->entityRepository->find($identifier); // ... if ($form->isValid()) { $this->entityRepository->save($entity); $this->mailer->send( Swift_Message::newInstance() ->setBody('Hey, something was updated!') ); } } }
  21. 21. Store the entity in-memory? final class InMemoryEntityRepository implements EntityRepository { private $entities = []; public function find(string $identifier) : ?Entity { return $this->entities[$identifier] ?? null; } public function save(Entity $entity) : Entity { $this->entities[$entity->getIdentifier()] = $entity; return $entity; } }
  22. 22. Multiple implementations: The Yaml bits # config/services.yaml services: _defaults: autoconfigure: true autowire: true # ... AppEntityRepository: alias: AppInfrastructureDoctrineDoctrineEntityRepository
  23. 23. Fast tests? # config/services_test.yaml services: # ... AppEntityRepository: alias: AppTestsInMemoryInMemoryEntityRepository
  24. 24. Event Dispatcher
  25. 25. Dispatching the event class MyController { public function __construct( EntityRepository $entityRepository, EventDispatcherInterface $eventDispatcher ) { /* ... */ } public function action(Request $request, string $identifier) { // ... if ($form->isValid()) { $this->entityRepository->save($entity); $this->eventDispatcher->dispatch( EntitySaved::NAME, new EntitySaved($entity) ); } // ... } }
  26. 26. An event class EntitySaved extends Event { const NAME = 'entity.saved'; private $entity; public function __construct(Entity $entity) { $this->entity = $entity; } public function getEntity() : Entity { return $this->entity; } }
  27. 27. A listener final class SendAnEmailWhenEntityIsSaved { public function __construct(MailerInterface $mailer) { /** ... **/ } public function onEntitySaved(EntitySaved $event) { $this->mailer->send(/** something **/); } }
  28. 28. Wiring it final class SendAnEmailWhenEntityIsSaved implements EventSubscriberInterface { // ... public static function getSubscribedEvents() { return [ EntitySaved::NAME => 'onEntitySaved', ]; } public function onEntitySaved(EntitySaved $event) { // ... } }
  29. 29. What is the point? 4 The controller just have to dispatch this event 4 We can create another listener easily 4 Much easier to group things per feature
  30. 30. Decorator
  31. 31. final class DispatchAnEventWhenEntityIsSaved implements EntityRepository { public function __construct( EntityRepository $decoratedRepository, EventDispatcherInterface $eventDispatcher ) { /** ... **/ } public function find(string $identifier) : ?Entity { return $this->decoratedRepository->find($identifier); } public function save(Entity $entity) : Entity { $saved = $this->decoratedRepository->save($entity); $this->eventDispatcher->dispatch( EntitySaved::NAME, new EntitySaved($saved) ); return $saved; } }
  32. 32. Decorates the repository: Plumbing! # config/services.yaml services: # ... AppEntityRepositoryDispatchAnEventWhenEntityIsSaved: decorates: AppEntityRepository arguments: - "@AppEntityRepositoryDispatchAnEventWhenEntityIsSaved.inner"
  33. 33. We just have to save class MyController { public function action(Request $request, $identifier) { // ... if ($form->isValid()) { $this->entityRepository->save($entity); } // ... } }
  34. 34. Decorates all the things!
  35. 35. What do we have? 4 Easy-to-change entity storage 4 Events dispatched regarding of the storage implementation 4 Easy-to-turn-on-and-off actions (on events) 4 Easily testable code!
  36. 36. Design patterns: they just help us to enable change
  37. 37. How to apply that... 4 Closes the door! 4 Uses final keyword 4 private properties 4 Create extension points when required 4 Prevent in case of
  38. 38. Maintainability tips 4 Distinct features in their own namespaces 4 Interfaces' names should reflect their responsibilities 4 Implementations' names should reflect their distinction
  39. 39. Thank you! @samuelroze birdie.care https://joind.in/talk/ae6c3

×