Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Modernising the Legacy (ZendCon)

Modernising the Legacy (ZendCon)

No one likes to work with the legacy projects - it's not fun. There are no specs, there are no behat examples and you're afraid to touch it. The customer may not have time or budget to spend on rewriting it from the scratch, but is likely to keep asking for the new features.

Learn how to work with the legacy code, how to add new features without breaking it. Learn to use Symfony components to support building sustainable features.

2bd48651cd01e0ca2e0a255a63da77aa?s=128

Marek Matulka

October 21, 2015
Tweet

More Decks by Marek Matulka

Other Decks in Programming

Transcript

  1. Modernising the Legacy Marek Matulka UK

  2. Marek Matulka Software Engineer SensioLabs UK @super_marek

  3. None
  4. Legacy

  5. What is legacy code? - old code - poor quality

    code - no environments - no error logging (or excessive logging) - no tests
  6. It’s too hard - understand the logic - add new

    features - debug - fix bugs - adopt new technologies
  7. How do we get out of legacy?

  8. None
  9. None
  10. None
  11. Example

  12. None
  13. None
  14. None
  15. Start with the goal

  16. Why? Business goal

  17. Why? Who? Who? Actors

  18. Why? Who? Who? How? How? How? Impacts

  19. Why? Who? Who? How? How? How? What? What? What? What?

    What? What? Deliverables
  20. Why? Who? Who? How? How? How? What? What? What? What?

    What? What? Prioritise
  21. Goal: Reduce drop-outs by 10% In order to see the

    total cost of order As a shopper I want to see postage cost Example Why? Who? How? What?
  22. Write scenarios Feature: Shopper can see postage cost In order

    to see the total cost of order As a shopper I want to see a postage cost Scenario: Shopper can see a postage cost Given I have added a "Clean Code" book priced £34.50 to the basket And the postage cost for one book is £3.50 When I check the basket Then I should see the postage cost of £3.50 And the total of the basket should be £38.00
  23. Implement scenarios

  24. Given-When-Then Feature: Shopper can see postage cost In order to

    see the total cost of order As a shopper I want to see a postage cost Scenario: Shopper can see a postage cost Given I have added a "Clean Code" book priced £34.50 to the basket And the postage cost for one book is £3.50 When I check the basket Then I should see the postage cost of £3.50 And the total of the basket should be £38.00
  25. (everything?) What to test?

  26. Unit tests Acceptance tests Integration tests End-to-end

  27. Unit tests Acceptance tests Integration tests End-to-end Manual Automated

  28. Unit tests Acceptance tests Integration tests End-to-end Slowest Fastest

  29. Why test?

  30. Why test? - code level documentation - features described through

    examples - clean code - you’re not afraid to change your code - peace of mind
  31. Why test? delivered features project’s life

  32. Why use Symfony components?

  33. Symfony Components The standard foundation on which the best PHP

    applications are built. - fully tested - decoupled - reusable - de-facto standard
  34. Symfony Components Build a micro framework. Use components you need

    in your application.
  35. standardised way to install components Composer

  36. None
  37. composer.json { "require": { "php": ">=5.6.0" }, "require-dev": { "phpspec/phpspec":

    "~2.0" }, "config": { "bin-dir": "bin" }, "autoload": {"psr-0": {"": "src"}} }
  38. $ sudo dnf install composer

  39. $ curl -sS https://getcomposer.org/installer | php

  40. $ composer install

  41. $ composer update

  42. $ composer update package/name

  43. $ composer require package/name

  44. symfony/dependency-injection Dependency Injection

  45. Dependency Injection In software engineering, dependency injection is a software

    design pattern that implements inversion of control for resolving dependencies. Dependency injection means giving an object its instance variables. Really. That's it. https://en.wikipedia.org/wiki/Dependency_injection
  46. Dependency Injection PostageCalculator PostageRepository

  47. Dependency Inversion PostageCalculator PostageRepository

  48. Dependency Inversion PostageCalculator PostageRepository PostageSqliteRepository

  49. Dependency Inversion PostageCalculator PostageRepository PostageSqliteRepository PostageDoctrineRepository

  50. DI as a boundary Legacy code Quality de- coupled code

    DI
  51. Install dependency injection $ composer require symfony/dependency-injection $ composer require

    symfony/config
  52. Create container.php <?php // app/container.php use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use

    Symfony\Component\Config\FileLocator; require __DIR__ . '/../vendor/autoload.php'; $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/app/config')); $loader->load('services.yml'); $container->compile();
  53. Create container.php <?php // app/container.php use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use

    Symfony\Component\Config\FileLocator; require __DIR__ . '/../vendor/autoload.php'; $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/app/config')); $loader->load('services.yml'); $container->compile();
  54. Create container.php <?php // app/container.php use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use

    Symfony\Component\Config\FileLocator; require __DIR__ . '/../vendor/autoload.php'; $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/app/config')); $loader->load('services.yml'); $container->compile();
  55. Create container.php <?php // app/container.php use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use

    Symfony\Component\Config\FileLocator; require __DIR__ . '/../vendor/autoload.php'; $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/app/config')); $loader->load('services.yml'); $container->compile();
  56. Create container.php <?php // app/container.php use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use

    Symfony\Component\Config\FileLocator; require __DIR__ . '/../vendor/autoload.php'; $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/app/config')); $loader->load('services.yml'); $container->compile();
  57. Create container.php <?php // app/container.php use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use

    Symfony\Component\Config\FileLocator; require __DIR__ . '/../vendor/autoload.php'; $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/app/config')); $loader->load('services.yml'); $container->compile();
  58. # app/config/services.yml services: acme.postage.repository: class: Acme\Infrastructure\Sqlite\PostageSqliteRepository acme.postage.calculator: class: Acme\Basket\PostageCalculator arguments:

    - @acme.postage.repository Create services.yml
  59. # app/config/services.yml services: acme.postage.repository: class: Acme\Infrastructure\Sqlite\PostageSqliteRepository acme.postage.calculator: class: Acme\Basket\PostageCalculator arguments:

    - @acme.postage.repository Create services.yml
  60. # app/config/services.yml services: acme.postage.repository: class: Acme\Infrastructure\Sqlite\PostageSqliteRepository acme.postage.calculator: class: Acme\Basket\PostageCalculator arguments:

    - @acme.postage.repository Create services.yml
  61. Use container require '../_inc/db.php'; require '../app/container.php'; // ... $postageCalculator =

    $container->get('acme.postage.calculator'); if ($postage = $postageCalculator->calculateForBasket($_SESSION['basket'])) { $postage = $postage->toView(); echo sprintf("<p>Estimated postage for %d item(s): £%1.02f.</p>", $postage['quantity'], $postage['price'] ); } // ...
  62. Use container require '../_inc/db.php'; require '../app/container.php'; // ... $postageCalculator =

    $container->get('acme.postage.calculator'); if ($postage = $postageCalculator->calculateForBasket($_SESSION['basket'])) { $postage = $postage->toView(); echo sprintf("<p>Estimated postage for %d item(s): £%1.02f.</p>", $postage['quantity'], $postage['price'] ); } // ...
  63. Use container require '../_inc/db.php'; require '../app/container.php'; // ... $postageCalculator =

    $container->get('acme.postage.calculator'); if ($postage = $postageCalculator->calculateForBasket($_SESSION['basket'])) { $postage = $postage->toView(); echo sprintf("<p>Estimated postage for %d item(s): £%1.02f.</p>", $postage['quantity'], $postage['price'] ); } // ...
  64. None
  65. Application Kernel

  66. container.php <?php // app/container.php use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\Config\FileLocator;

    require __DIR__ . '/../vendor/autoload.php'; $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/app/config')); $loader->load('services.yml'); $container->compile();
  67. container.php <?php // app/container.php use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\Config\FileLocator;

    require __DIR__ . '/../vendor/autoload.php'; $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/app/config')); $loader->load('services.yml'); $container->compile();
  68. <?php # src\Acme\Application\Kernel.php namespace Acme\Application; class Kernel { /** @var

    ContainerBuilder */ private $container; public function boot() { $this->container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/app/config')); $loader->load('services.yml'); $this->container->compile(); } public function getContainer() { return $this->container; } }
  69. container.php <?php // app/container.php require __DIR__ . '/../vendor/autoload.php'; $kernel =

    (new \Acme\Application\Kernel())->boot(); $container = $kernel->getContainer();
  70. Singleton Kernel

  71. <?php # src\Acme\Application\Kernel.php namespace Acme\Application; class Kernel { public static

    $instance; // ... public static getInstance() { if (null === static::$instance) { static::$instance = (new static())->boot(); } return static::$instance; } protected function __construct() {} private function __clone() {} private function __wakeup() {} }
  72. <?php # src\Acme\Application\Kernel.php namespace Acme\Application; final class Kernel { public

    static $instance; // ... public static getInstance() { if (null === static::$instance) { static::$instance = (new static())->boot(); } return static::$instance; } protected function __construct() {} private function __clone() {} private function __wakeup() {} }
  73. $di = Kernel::getInstance()->getContainer(); $service = $di->get('acme.service.name');

  74. Dependency Injection with Drupal 7?

  75. container.php <?php require_once DRUPAL_ROOT . '/../vendor/autoload.php'; $kernel = (new \Acme\Application\Kernel())->boot();

    variable_set('di_container', $kernel->getContainer());
  76. container.php <?php require_once DRUPAL_ROOT . '/../vendor/autoload.php'; $kernel = (new \Acme\Application\Kernel())->boot();

    variable_set('di_container', $kernel->getContainer());
  77. public/sites/default/settings.php <?php // ... include_once 'config/container.php'; include 'database.php'; // ...

  78. depot_locator.module <?php function get_depot_json($postcode) { $depotEntity = variable_get('di_container') ->get('acme.depot_locator')->locateDepot($postcode); $depot

    = $depotEntity->toArray(); set_depot_cookies($depot); return ['depot' => $depot]; }
  79. depot_locator.module <?php function get_depot_json($postcode) { $depotEntity = variable_get('di_container') ->get('acme.depot_locator')->locateDepot($postcode); $depot

    = $depotEntity->toArray(); set_depot_cookies($depot); return ['depot' => $depot]; }
  80. symfony/console Add console commands

  81. Install console component $ composer require symfony/console

  82. class LocateDepotCommand extends Command { /** @var DepotLocator */ private

    $depotLocator; public function __construct(DepotLocator $depotLocator) { $this->depotLocator = $depotLocator; parent::__construct(); } protected function configure() { $this->setName('depot:locate') ->addArgument('postcode', InputArgument::REQUIRED); } protected function execute(InputInterface $input, OutputInterface $output) { $this->depotLocator->locateDepot($input->getArgument('postcode')); $output->writeln('Nearest depot is located at: ' . $depot->getAddress()); } }
  83. app/console #!/usr/bin/php <?php require_once (__DIR__ . '/../vendor/autoload.php'); require_once (__DIR__ .

    '/app/container.php'); use Symfony\Component\Console\Application; $application = new Application(); $application->addCommands([ $container->get('acme.command.depot_locate'), ]); $application->run();
  84. $ app/console depot:locate wc1a1dg

  85. twig/twig Twig

  86. What is twig?

  87. None
  88. None
  89. Install twig $ composer require twig/twig

  90. How to use twig? <?php $loader = new Twig_Loader_Filesystem('/path/to/templates'); $twig

    = new Twig_Environment($loader); echo $twig->render('index.html', ['variable' => 'value']);
  91. # app/config/services.yml parameters: twig.paths: - app/Resources/views services: twig.template_loader: class: Twig_Loader_Filesystem

    arguments: - %twig.paths% twig.renderer: class: Twig_Environment arguments: - @twig.template_loader Enabling twig in DI container
  92. # app/config/services.yml parameters: twig.paths: - app/Resources/views services: twig.template_loader: class: Twig_Loader_Filesystem

    arguments: - %twig.paths% twig.renderer: class: Twig_Environment arguments: - @twig.template_loader Enabling twig in DI container
  93. # app/config/services.yml parameters: twig.paths: - app/Resources/views services: twig.template_loader: class: Twig_Loader_Filesystem

    arguments: - %twig.paths% twig.renderer: class: Twig_Environment arguments: - @twig.template_loader Enabling twig in DI container
  94. # app/config/services.yml parameters: twig.paths: - app/Resources/views services: twig.template_loader: class: Twig_Loader_Filesystem

    arguments: - %twig.paths% twig.renderer: class: Twig_Environment arguments: - @twig.template_loader Enabling twig in DI container
  95. Use twig $basketViewData = $container->get('acme.basket.view') ->toView($_SESSION['basket']); $basketView = $container->get('twig.renderer') ->render(

    'basket.twig.html', $basketViewData ); echo $basketView;
  96. symfony/http-foundation Decouple from global state

  97. Http application’s flow Controller Request Response

  98. Install HttpFoundation component $ composer require symfony/http-foundation

  99. De-coupling from global state # /public/basket.php <?php require __DIR__ .

    '/../app/container.php'; use Symfony\Component\HttpFoundation\Request; $request = Request::createFromGlobals(); $response = $container->get('acme.basket_view.controller') ->viewAction($request); $response->send();
  100. De-coupling from global state # /public/basket.php <?php require __DIR__ .

    '/../app/container.php'; use Symfony\Component\HttpFoundation\Request; $request = Request::createFromGlobals(); $response = $container->get('acme.basket_view.controller') ->viewAction($request); $response->send();
  101. De-coupling from global state # /public/basket.php <?php require __DIR__ .

    '/../app/container.php'; use Symfony\Component\HttpFoundation\Request; $request = Request::createFromGlobals(); $response = $container->get('acme.basket_view.controller') ->viewAction($request); $response->send();
  102. De-coupling from global state # /public/basket.php <?php require __DIR__ .

    '/../app/container.php'; use Symfony\Component\HttpFoundation\Request; $request = Request::createFromGlobals(); $response = $container->get('acme.basket_view.controller') ->viewAction($request); $response->send();
  103. Going forward

  104. Try it yourself! https://github.com/mareg/legacy-summercamp-2015 - four exercises: - add dependency

    injection - add twig - decouple from global state - controller as service
  105. Questions? Slides: speakerdeck.com/super_marek Feedback: joind.in/talk/view/15567 Connect on twitter: @super_marek