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

Marrying front with back end

Marrying front with back end

from PHPBenelux 2014

Bastian Hofmann

January 25, 2014
Tweet

More Decks by Bastian Hofmann

Other Decks in Programming

Transcript

  1. Rapid Development so that you can develop new features quickly

    without breaking the rest of your application or accumulation lots of technical debt
  2. Handling large code-bases especially if your code base becomes larger

    and larger, developed by big, growing teams
  3. Frameworks to the rescue Normally if faced with these problems

    people say: don't reinvent the wheel, let's look what's already out there, let's use some framework (or some libraries), or if you have a bad case of the not-invented-here syndrom in your company, you are going to develop your own
  4. webserver HTML browser JS so the normal flow of a

    web application is that some server code serves some html (and maybe some apis) to the browser, in the browser there is some (or a lot of) javascript that manipulates the DOM
  5. webserver HTML browser JS Ajax and either links to other

    pages served by the server or does ajax requests back to the server. this concept is mostly true for either traditional apps as well as single page applications
  6. webserver HTML browser JS Ajax but the code in both

    worlds, server and client, is seldom connected
  7. de duplication ode duplication code duplication code duplication code duplication

    code duplication code duplication code duplication code duplication code duplication code duplication code duplication code duplication code duplicatio code duplicat code duplic code dup code du code cod co co which leads to lot of code duplication in templates, validation logic, models and lots of boiler plate code for communication between server and client, marshalling data
  8. ResearchGate gives science back to the people who make it

    happen. We help researchers build reputation and accelerate scientific progress. On their terms. ‟ the goal is to give...
  9. Questions? Ask by the way, if you have any questions

    throughout this talk, if you don't understand something, just raise your hand and ask.
  10. if we take a small peek into a possible future

    of web application development
  11. Meteor http://www.meteor.com or meteor, that try to bridge the gap

    between server and client. but they are still very alpha, good for prototyping, writing small apps, trying things out, but personally I wouldn't create a big million lines of code web application with 40+ developers yet
  12. Incremental Refactoring the way to make the architecture of your

    existing application better and connect your backend with your frontend code is incremental refactoring, since you hopefully can't afford to sit down, stop development for 6 months and rewrite everything
  13. many roads of course like always there are many ways

    to go about that, which totally depends on you existing code
  14. or what i'm going to talk about for the reminder

    of the talk, what we did at RG
  15. status quo so RG: when we started about over a

    year ago, the status quo was:
  16. on the frontend yui3, but every page was built with

    custom modules, not much reuse of existing modules but very basic ones (also some legacy pages with yui2, prototype.js and scriptaculous)
  17. Components let's rethink the way we are building pages or

    our whole application and separate it into small components
  18. so looking at a page (that's what our profile looked

    like over a year ago), you can identify lots of small components nested into each other on a page
  19. Server JS Browser JSON HTML HTML so it should have

    it's own url, and for seo reasons can just be included in a page rendered to a browser by the server or can be fetched separately or nested within other components by the apps javascript, where we only wanted to transport the data to the client and render it into html there
  20. JS is part of the component the javascript to bind

    on dom events and manipulate the components should be part of the component
  21. Share code between server and client and we wanted to

    share as much code between server and client as possible (considering our heterogeneous architectur, js client, php server)
  22. It needs to be fast of course ... concerning performance

    as well as development speed and productivity
  23. PHP Controller Mustache Template JavaScript view class Widget Providing data

    Handling browser events Displaying data CSS so to sum it up an widget contains
  24. Profile Publications Publication Publication Publication AboutMe LeftColumn Image Institution Menu

    we see, that it's actually kind of a tree structure, for the sake of this presentation i simplified it slightly, actually our profile consists of over 200 components
  25. Profile Publications Publication Publication Publication AboutMe LeftColumn Image Menu Server

    Request Response Institution i said earlier, that all these components have their own URL. So they can be requested and rendered by the client seperately. For better user experience on the first load or SEO reasons these components can also be bundled together and rendered in a single page load on the backend.
  26. LeftColumn Image Menu Server Request Response if we want to

    fetch the left column separately it looks like this
  27. Widget Requirement this tree structure is achieved through so called

    widget requirements, why they are called requirements
  28. Profile Publications Publication Publication Publication AboutMe LeftColumn Image Menu Institution

    that means the profile widget requires: publications, aboutMe, leftColumn and institution
  29. Profile Publications Publication Publication Publication AboutMe LeftColumn Image Menu Institution

    and Publications requires several publicationItem widgets and leftColumn the Image and the Menu widget
  30. Do not fetch data directly so something you shouldn't do

    is fetching this data directly on you server when composing a page or a subpage
  31. Profile Publications Publication Publication Publication AboutMe LeftColumn Image Menu Account

    Account Account Account Account Publication1 Publication2 Publication3 Institution if we take our simplified example, a lot of components need the account of the user that's displayed, while that could be solved with in memory caching, a list of publications each need the publication entity, if we display 20 publications, that would mean 20 database queries, doing it in one query would be much faster though, and you have lot's of stuff like this
  32. Require stuff so instead of fetching stuff directly, it's way

    better to require stuff (that's also why building up the widget tree was done with widget "requirements"
  33. http://www.infoq.com/presentations/Evolution-of-Code- Design-at-Facebook/ this concept is actually not that new, one

    small company who is doing this very much is for example facebook, who also did a very good talk about this a few years back
  34. so how does it work? around all your components that

    just state data (or widget) requirements you need an instance called a preparer
  35. Widget Widget Widget Widget Preparer Fetch Requirements Resolver Resolver Services

    Connector Interfaces Connector Implementations the preparer iterates over all components and fetches their requirments
  36. Widget Widget Widget Widget Preparer Resolver Resolver Services Connector Interfaces

    Connector Implementations Batch requirements and pass them to resolvers it batches them together as intelligently as possible, passes the requirements to resolvers
  37. Widget Widget Widget Widget Preparer Resolver Resolver Services Connector Interfaces

    Connector Implementations Call Services as effective as possible (Multi-GET,...) which call the services/storages/etc as effective as possible, or just execute some service class methods
  38. Widget Widget Widget Widget Preparer Resolver Resolver Services Connector Interfaces

    Connector Implementations Attach fetched data to Requirements and pass them back to the preparer the fetched data is attached to the requirements, passed back to the preparer
  39. Widget Widget Widget Widget Preparer Resolver Resolver Services Connector Interfaces

    Connector Implementations Distribute fetched data to the widgets that required it who in turn distributes the fetched data to the components
  40. class Widget { /** @var Request */ public $request; public

    $account; public $scienceDisciplines; public function collect() { return new RequirementCollection([ new EntityRequirement( 'account', Account::class, ['id' => $this->request->get('id')] ), ], function() { return new RequirementCollection([ new ServiceRequirement( 'scienceDisciplines', AccountService::class, 'getScienceDisciplines', ['account' => $this->account] ) ]); }); } } in code... you can imagine if you are not careful this can become some kind of a callback hell
  41. Request Cache nice thing is you can cache this stuff

    intelligently in memory of your current request
  42. class Widget { /** @var Request */ public $request; public

    $account; public $scienceDisciplines; public function collect() { return new RequirementCollection([ new EntityRequirement( 'account', Account::class, ['id' => $this->request->get('id')] ), ], function() { return new RequirementCollection([ new ServiceRequirement( 'scienceDisciplines', AccountService::class, 'getScienceDisciplines', ['account' => $this->account] ) ]); }); } } as you are seeing here
  43. public function collect() { return new RequirementCollection([ new EntityRequirement( 'account',

    Account::class, ['id' => $this->request->get('id')] ), ], function() { return new RequirementCollection([ new ServiceRequirement( 'scienceDisciplines', AccountService::class, 'getScienceDisciplines', ['account' => $this->account] ) ]); }); } in code... you can imagine if you are not careful this can become some kind of a callback hell
  44. <?php function someGenerator() { yield 'start of the generator'; for

    ($i = 1; $i <= 4; $i++) { // Note that $i is preserved between yields. if ($i % 2 === 0) { yield $i; } } if (rand(1, 2) === 1) { // this closes the generator return; } yield anotherFunction(); // this is also executed } function anotherFunction() { return 'result from another function'; } foreach (someGenerator() as $value) { echo "$value\n"; } start  of  the  generator 2 4 result  from  another  function start  of  the  generator 2 4
  45. public function collect() { yield [ new EntityRequirement( 'account', Account::class,

    ['id' => $this->request->get('id')] ), ]; yield [ new ServiceRequirement( 'scienceDisciplines', AccountService::class, 'getScienceDisciplines', ['account' => $this->account] ) ]; } because then you can write it like this:
  46. trait ServiceRequirementFactory { /** @return $this */ public static function

    getCall() { return new ServiceRequirementFactoryProxy( ! ! ! static::class ! ! ! ); } }
  47. class ServiceRequirementFactoryProxy { private $className; public function __construct($className) { $this->className

    = $className; } public function __call($name, $arguments) { return [ 'serviceClass' => $this->className, 'methodName' => $name, 'arguments' => $arguments ]; } }
  48. Profile Publications Publication Publication Publication AboutMe LeftColumn Image Menu Institution

    e.g. for a list of publications that you got from a solr search, you may not want to go to the database again to fetch each publication in each list item, but since a list item is supposed to be renderable separately as well, it needs this logic in there
  49. class PublicationKeywordSearch { public $publications; public $publicationListItems = []; public

    function collect() { yield [ serviceRequirement( 'publications', PublicationService::getCall()->getByKeywords( ['virology', 'cancer'], 10, 0 ) ) ]; foreach ($this->publications as $publication) { yield new WidgetRequirement( 'publicationListItems', PublicationItem::CLASS, [ ! ! ! ! ! ! ! ! 'publicationId' => $publication->getId(), ! ! ! ! ! ! ! ! 'publication' => $publication ! ! ! ! ! ! ! ] ); } } } in code
  50. class PublicationItem { public $publicationId; public $publication; public function collect()

    { yield new RequestDataRequirement('publicationId'); yield [ new EntityRequirement( 'publication', Publication::class, ['id' => $this->publicationId] ) ]; } } that means if the subwidget has a requirment like this, the preparer would directly put the prefilled data in there instead of passing it on to the resolvers
  51. Whoa, this looks awfully complicated to debug you're right, it

    takes a bit of time to get used to program this way, but everyone who joined our company in the last few months since we are doing it says after a week or so, that they actually can't imagine working any other way again (i'll talk more about the benefits later)
  52. but still it's complex, so a good thing is taking

    a bit of effort to make it as transparent as possible to see what happens in your application (which is a very good thing anyways). we have a debug toolbar that shows all the component on the page
  53. HTML i said earlier we want our widget tree to

    be renderable on the server side as html
  54. JSON and just put out as json and then be

    rendered on the client side by our javascript
  55. Mustache } http://mustache.github.com/ so we decided to use mustache templates,

    we are actually using twitters mustache implementation called hogan
  56. <div id="{{widgetId}}"> <h3> Publications <a href="javascript:" class="js-showAll"> ({{count}}) </a> </h3>

    <ul> {{#publicationItems}} <li>{{{.}}}</li> {{/publicationItems}} </ul> {{#showLegalFooter}} {{{legalFooter}}} {{/showLegalFooter}} </div> that's what a template may look like
  57. Helper Methods there is also a php implementation of mustache,

    but it's not the fastest and one thing is, that mustache oftentimes relies on small helper functions
  58. •nl2br •truncate •pluralize •wordwrap •highlight •... like ... if you

    now use a php implementation on the server and a js implementation on the client, we have to develop these functions twice ... not a good idea
  59. http://pecl.php.net/package/v8js V8js that why we actually execute javascript through a

    php extension that makes the v8 js library available on the server. so we are executing the same code on the server and on the client to render the same templates. suprise: it's acutally really really fast
  60. JavaScript so we handled templates and rendering, the backend controllers

    that provide the data, on the javascript side in the client each component can have a view object to bind on DOM events
  61. <div id="{{widgetId}}"> <h3> Publications <a href="javascript:" class="js-showAll"> ({{count}}) </a> </h3>

    <ul> {{#publicationItems}} <li>{{{.}}}</li> {{/publicationItems}} </ul> {{#showLegalFooter}} {{{legalFooter}}} {{/showLegalFooter}} </div> remember this template
  62. YUI.add('views.publicationList', function (Y) { Y.views.publicationList = Y.Base.create(Y.WidgetView, { events :

    { '.js-showALl' : { click : 'showALl' } }, showAll : function () { var node = this.get('container'); node.addClass('loading'); Y.loadWidget(‚/publications/all', { keywords : this.data.keywords }, function (widget) { widget.render({ replace : node }); }); } }); }); here is an example
  63. if you think about this a bit more, every component

    having it's own template, javascript and maybe css
  64. http://www.youtube.com/watch?v=fqULJBBEVQE .. this is exactly what web components is about.

    they have their own html, css, js and are even more sandboxed through a shadow dom to limit interactions between different components. an example for webcomponents are the browser controls for videos or forms by the way.
  65. <polymer-element name="tk-element" attributes="owner color"> <template> <span>This is <strong>{{owner}}</strong>'s tk-element.</span> <span

    id="el" style="color: {{color}}">Not ready...</span> </template> <script> Polymer('tk-element', { owner: "Bastian", color: "red", ready: function() { this.$.el.innerText = this.owner + " is ready!"; } }); </script> </polymer-element>
  66. Easier Refactoring even if the implementation of one component is

    very ugly and crude, at least it's encapsulated (hopefully tested) and you can either leave it or revisit this component later on
  67. Profile Publications Publication Publication Publication AboutMe LeftColumn Image Menu EXCEPTION

    Institution if an exception occurs in one of our components while fulfilling a requirement that is not optional
  68. Profile Publications Publication Publication Publication LeftColumn Image Menu Institution we

    just deactivate this component and the rest of the page is still functional
  69. we are doing this excessively, and have over 90 or

    so experiments with sometimes over 20 variants running. the way we can do this quickly and easily is by just switching components for the different variants
  70. Profile Publications Publication Publication Publication AboutMe LeftColumn Image Menu <esi:include

    src="..." /> Institution because every component has it's own url you can just render out a esi placeholder instead of the widget to tell varnish to fetch it separately and provided it has caching headers, get it out of the cache
  71. Load components asynchronously the same way you can also load

    components of the widget tree asynchronously
  72. Profile Publications Publication Publication Publication AboutMe LeftColumn Image Menu <div

    id="placeholder"></div> <script>loadWidget('/aboutMe', function(w) { w.render({ replace : '#placeholder' }); })</script> Institution so instead of rendering the widget you render a placeholder dom element and a script tag that loads the widget with an ajax request and then renders it on the client side
  73. if you look at your widget tree you can mostly

    identify larger parts, which are widgets itself
  74. Profile Menu Header LeftColumn RightColumn like this, so what you

    can do to dramatically increase the perceived load time is prioritizing the rendering
  75. so our http request looks like this, first you compute

    and render the important parts of the page, like the top menu and the profile header as well as the rest of the layout, for the left column and right column which are expensive to compute you just render placeholders and then flush the content to the client so that the browser already renders this
  76. still in the same http request you render out the

    javascript needed to make the already rendered components work, so people can use the menu for example
  77. still in the same http request you then compute the

    data for the left column and render out some javascript that takes this data and renders it into the components template client side and then replaces the placeholder with the rendered template
  78. still in the same request you then can do this

    with the right column -> flush content as early as possible, don't wait for the whole site to be computed
  79. pushState and if you are at that, when you switch

    pages, you can also just load the differences between and use pushState to change the url (if supported) to make your app faster