Integrating React.js into a PHP Application
@AndrewRota | #BGPHP16
JavaScript Ecosystem
Software Engineer at wayfair.com
JavaScript Platform Team
@AndrewRota
Boston, MA
Andrew Rota
Let’s take a step back.
Traditional Website Lifecycle
ServerBrowser
HTML Response
HTML Request
ServerBrowser
HTML Response
HTML Request
ServerBrow...
Traditional Website Stack
Server-Side MVC Framework
Data Persistance
JavaScript
Single Page Application
Lifecycle
Browser
HTML Response
HTML Request
Server
Data Response
Data Request
Server
Data Respons...
Single Page Application
Stack
Server-Side MVC Framework
Data Persistance
JavaScript
• Introducing React.js
• Client-Side React.js with PHP
• Server-side rendering React.js with PHP
• JSX
• Fallback to serve...
What is React.js?
“A JavaScript library for building user interfaces”
Component driven
Composable, reusable, testable
Entire component
re-renders on data change
No more manual DOM manipulation!
Implemented under the hood
with “virtual DOM” ...
“Learn once,
write anywhere”
React Native for native iOS and Android Apps
var Greeting = React.createClass({

render: function() {

return <strong>

Hello, {this.props.name}!

</strong>;

}

});

...
var Greeting = React.createClass({

displayName: "Greeting",



render: function render() {

return React.createElement(

...
var Greeting = React.createClass({

render: function() {

return <strong>

Hello, {this.props.name}!

</strong>;

}

});

...
React.createClass({

// ...

render: function() {

return (

<div>

<h3>TODO</h3>

<TodoList items={this.state.items} />

...
Client-Side Rendering
JavaScript
renders react.js
app
Nearly-blank
page load
JavaScript
PHP
React.js Clientside
Advantages of rendering
React.js client-side
• Server-agnostic
• Isolates UI layer to one technology: JavaScript
• Least a...
For many apps, client-side rendering
with React.js is the most practical
and least complex approach
So why might I need
server-side rendering (SSR)?
• Performance sensitive applications
• Search engine optimization
• Site ...
Server-Side Rendering +
Performance
More control to reduce time to first meaningful paint
Client-Side
+SSR
JS
Loads
Rendere...
SEO
• Allow site to be crawled by Search engines which don’t
execute JavaScript
• Google does crawl sites with JavaScript,...
Site works without JavaScript
• You may have users who disable JavaScript in their
browser (for example by using NoScript)...
Don’t let JavaScript
become a single point of
failure
React.js SSR
var Greeting = React.createClass({

render: function() {

return <strong>

Hello, {this.props.name}!

</strong>;

}

});

...
var Greeting = React.createClass({

render: function() {

return <strong>

Hello, {this.props.name}!

</strong>;

}

});

...
var Greeting = React.createClass({

render: function() {

return <strong>

Hello, {this.props.name}!

</strong>;

}

});

...
This is great if our
server runs JavaScript
The easiest way to do
React.js SSR is by running
Node.js on the server
“Universal JavaScript”
Server-Side JavaScript
Client-Side JavaScript
But what if your
server is PHP?
Two options for SSR with
PHP on the server side
React.js SSR with a
Node.js Service
React
Node.js
service
JavaScript
PHP
React.js Clientside
curl -X POST
-H 'Content-Type: application/json'
-d ‘{"path":"./resources/assets/js/Greeting.js", "data": {"name":
"BGPHP"...
<?php

$component_name = 'Greeting';

$ch = curl_init("https://nodeserver.local:3333/");

$props = ["name" => "BGPHP"];

$...
But what if we could
execute JavaScript from
within PHP…
React.js SSR with
PHP’s V8Js
JavaScript
PHP .
React.js Clientside
React.js
V8Js
What is V8Js?
https://pecl.php.net/package/v8js
Installing V8Js
• If you’re lucky there might be a binary available,
otherwise…
• Build and install the latest version of ...
- php v8js docs
“it's way more tedious to install
V8Js on Windows”
Oh, and…
Success!
<?php

$v8 = new V8Js();

echo($v8->executeString("

var name = 'World';

const GREETING = 'Hello';

function greeting(str...
nacmartin/phpexecjs
V8js or node.js subprocess
JavaScript
PHP .
React.js Clientside
V8JsNode.js
<?php

$phpexecjs = new PhpExecJs();

echo($phpexecjs->evalJs("

var name = 'World';

const GREETING = 'Hello';

function ...
reactjs/react-php-v8js
<?php

$react_source = file_get_contents(__DIR__ . 'path/to/react-bundle.js');

$app_source = file_get_contents(__DIR__ . ...
talyssonoc/react-laravel


<div>

@react_component('Hello', $data )

</div>

Route::get('/foo', function() {

return view('foo', ['data' => [ 'name...
Limenius/ReactBundle
phpexecjs or node.js service
(for Symfony)
node.js server
Easier to install, update
Standard environment
for running react.js on
the server
Maintain separate
server
...
And remember, for any of these
options:
+ Cache in production!
So what about
all that JSX?
ReactDOM.render(<Greeting name="World"/>, el);

Technically, this isn’t JavaScript
ReactDOM.render(<Greeting name="World"/>, el);

Babel to the rescue!
ReactDOM.render(React.createElement(Greeting,
{ name:...
Babel: Option 1
1. Transform JSX to JS on file change
2. Consume transformed bundle in V8js or
node.js render server
Use g...
e.g., Using Laravel Elixir
and Browserify
elixir.config.js.browserify.transformers.push({

name: 'babelify',

options: {}
...
Babel: Option 2
1. Use babel’s require hook
2. Also requires standalone build for
production
(only for dev, node.js)
npm i...
…without JavaScript.
Let’s talk functionality
• Use real links instead of buttons for navigation
• Use forms with real submit actions for mutating data
• Test without J...
this isn’t really a talk
about React.js
…or even PHP.
But…
Let’s go a couple
levels higher
What does MVC mean in a
world of JavaScript
frameworks?
View cohesion
Separate by concerns,
not technologies
Architecture over
individual technologies
Architecture over Technologies
• React.js and PHP can work great together
• But there are other options for client/server ...
Architecture over
individual technologies
The library you choose is less important
than how you choose to use it
Takeaways
• React.js is most easily integrated in a PHP app if
you’re ok with client-side only rendering
• If you want ser...
@AndrewRota
Благодаря!
Thank you!
Prochain SlideShare
Chargement dans…5
×

Integrating React.js Into a PHP Application

38 094 vues

Publié le

React.js has taken the web development world by storm, and for good reason: React offers a declarative, component-oriented approach to building highly-scalable web UIs. But how can we take advantage of a JavaScript library like React in our server-side PHP applications. In this talk l cover the different ways React.js can be integrated into an existing PHP web application: from a client-side only approach to multiple techniques that support full server-side rendering with a Node.js server or PHP’s v8js. I also discuss the trade-offs in each of these designs and the challenges involved with adding React to a PHP site. Most importantly, I consider the higher-level issue of how to improve view cohesion across the client-server divide in a PHP application.

Publié dans : Logiciels

Integrating React.js Into a PHP Application

  1. 1. Integrating React.js into a PHP Application @AndrewRota | #BGPHP16
  2. 2. JavaScript Ecosystem
  3. 3. Software Engineer at wayfair.com JavaScript Platform Team @AndrewRota Boston, MA Andrew Rota
  4. 4. Let’s take a step back.
  5. 5. Traditional Website Lifecycle ServerBrowser HTML Response HTML Request ServerBrowser HTML Response HTML Request ServerBrowser HTML Response HTML Request
  6. 6. Traditional Website Stack Server-Side MVC Framework Data Persistance JavaScript
  7. 7. Single Page Application Lifecycle Browser HTML Response HTML Request Server Data Response Data Request Server Data Response Data Request Server
  8. 8. Single Page Application Stack Server-Side MVC Framework Data Persistance JavaScript
  9. 9. • Introducing React.js • Client-Side React.js with PHP • Server-side rendering React.js with PHP • JSX • Fallback to server functionality • What does it all mean?
  10. 10. What is React.js? “A JavaScript library for building user interfaces”
  11. 11. Component driven Composable, reusable, testable
  12. 12. Entire component re-renders on data change No more manual DOM manipulation! Implemented under the hood with “virtual DOM” engine.
  13. 13. “Learn once, write anywhere” React Native for native iOS and Android Apps
  14. 14. var Greeting = React.createClass({
 render: function() {
 return <strong>
 Hello, {this.props.name}!
 </strong>;
 }
 });
 
 ReactDOM.render(<Greeting name="World"/>, el);

  15. 15. var Greeting = React.createClass({
 displayName: "Greeting",
 
 render: function render() {
 return React.createElement(
 "strong",
 null,
 "Hello, ",
 this.props.name,
 "!"
 );
 }
 });
 
 ReactDOM.render(React.createElement(
 Greeting,
 {name: "World"}),
 el);
  16. 16. var Greeting = React.createClass({
 render: function() {
 return <strong>
 Hello, {this.props.name}!
 </strong>;
 }
 });
 
 ReactDOM.render(<Greeting name="World"/>, el);

  17. 17. React.createClass({
 // ...
 render: function() {
 return (
 <div>
 <h3>TODO</h3>
 <TodoList items={this.state.items} />
 <form onSubmit={this.handleSubmit}>
 <input onChange={this.onChange} value={this.state.text} />
 <button>{'Add #' + (this.state.items.length + 1)}</button>
 </form>
 </div>
 );
 }
 });
 This is today’s demo based on the simple todo list app from facebook.github.io/react/
  18. 18. Client-Side Rendering
  19. 19. JavaScript renders react.js app Nearly-blank page load
  20. 20. JavaScript PHP React.js Clientside
  21. 21. Advantages of rendering React.js client-side • Server-agnostic • Isolates UI layer to one technology: JavaScript • Least amount of client-server sync complexity • Easiest way to get started with React.js
  22. 22. For many apps, client-side rendering with React.js is the most practical and least complex approach
  23. 23. So why might I need server-side rendering (SSR)? • Performance sensitive applications • Search engine optimization • Site needs to work without JavaScript
  24. 24. Server-Side Rendering + Performance More control to reduce time to first meaningful paint Client-Side +SSR JS Loads Rendered Interactive JS Loads
  25. 25. SEO • Allow site to be crawled by Search engines which don’t execute JavaScript • Google does crawl sites with JavaScript, though, so this may be less of an issue today
  26. 26. Site works without JavaScript • You may have users who disable JavaScript in their browser (for example by using NoScript) • The user should be able to interact with the site before JavaScript downloads • The site’s JavaScript fails to load 
 (poor connection, CDN issue, etc.)
  27. 27. Don’t let JavaScript become a single point of failure
  28. 28. React.js SSR
  29. 29. var Greeting = React.createClass({
 render: function() {
 return <strong>
 Hello, {this.props.name}!
 </strong>;
 }
 });
 
 ReactDOM.render(<Greeting name="World"/>, el);

  30. 30. var Greeting = React.createClass({
 render: function() {
 return <strong>
 Hello, {this.props.name}!
 </strong>;
 }
 });
 
 ReactDOMServer.renderToStaticMarkup(<Greeting name="World"/>); <strong>Hello, World!</strong>
  31. 31. var Greeting = React.createClass({
 render: function() {
 return <strong>
 Hello, {this.props.name}!
 </strong>;
 }
 });
 
 ReactDOMServer.renderToString(<Greeting name="World"/>); <strong data-reactroot="" data-reactid="1" data-react- checksum="1367554571"><!-- react-text: 2 -->Hello, <!-- /react- text --><!-- react-text: 3 -->World<!-- /react-text --><!-- react-text: 4 -->!<!-- /react-text --></strong>
  32. 32. This is great if our server runs JavaScript
  33. 33. The easiest way to do React.js SSR is by running Node.js on the server
  34. 34. “Universal JavaScript”
  35. 35. Server-Side JavaScript Client-Side JavaScript
  36. 36. But what if your server is PHP?
  37. 37. Two options for SSR with PHP on the server side
  38. 38. React.js SSR with a Node.js Service
  39. 39. React Node.js service JavaScript PHP React.js Clientside
  40. 40. curl -X POST -H 'Content-Type: application/json' -d ‘{"path":"./resources/assets/js/Greeting.js", "data": {"name": "BGPHP"}}' http://127.0.0.1:3333/ <div data-reactroot="" data-reactid="1" data-react- checksum="-520141946"><strong data-reactid="2"><!-- react-text: 3 -- >Hello, <!-- /react-text --><!-- react-text: 4 -->BGPPH<!-- /react- text --><!-- react-text: 5 -->!<!-- /react-text --></strong></div>
  41. 41. <?php
 $component_name = 'Greeting';
 $ch = curl_init("https://nodeserver.local:3333/");
 $props = ["name" => "BGPHP"];
 $data = ["data" => $props, "path" => "./resources/assets/js/" . $component_name . ".js"];
 $data_string = json_encode($data);
 $props_string = json_encode($props);
 
 curl_setopt(/* … */); $result = curl_exec($ch); <div id="app"><?= $result ?></div> 
 <script src="{{ asset('js/react-bundle.js') }}"></script>
 <script src="{{ asset('js/components.js') }}”></script> 
 <script>ReactDOM.render(React.createElement(<?= $component_name ?>, "<?= $props_string ?>"), document.getElementById('app'));</script>
  42. 42. But what if we could execute JavaScript from within PHP…
  43. 43. React.js SSR with PHP’s V8Js
  44. 44. JavaScript PHP . React.js Clientside React.js V8Js
  45. 45. What is V8Js? https://pecl.php.net/package/v8js
  46. 46. Installing V8Js • If you’re lucky there might be a binary available, otherwise… • Build and install the latest version of v8 • Build and install php-v8js • Enable the v8js extension in PHP • extension=v8js.so
  47. 47. - php v8js docs “it's way more tedious to install V8Js on Windows” Oh, and…
  48. 48. Success!
  49. 49. <?php
 $v8 = new V8Js();
 echo($v8->executeString("
 var name = 'World';
 const GREETING = 'Hello';
 function greeting(str) {
 return GREETING + ‘, ' + str + '!';
 }
 
 greeting(name);
 ")); JS!!!
  50. 50. nacmartin/phpexecjs V8js or node.js subprocess
  51. 51. JavaScript PHP . React.js Clientside V8JsNode.js
  52. 52. <?php
 $phpexecjs = new PhpExecJs();
 echo($phpexecjs->evalJs("
 var name = 'World';
 const GREETING = 'Hello';
 function greeting(str) {
 return GREETING + ‘, ' + str + '!';
 }
 
 greeting(name);
 "));
  53. 53. reactjs/react-php-v8js
  54. 54. <?php
 $react_source = file_get_contents(__DIR__ . 'path/to/react-bundle.js');
 $app_source = file_get_contents(__DIR__ . 'path/to/components.js'); 
 $rjs = new ReactJS($react_source, $app_source);
 $rjs->setComponent('Greeting', [ 'name' => 'world' ]); ?> <div id="app"><?= $rjs->getMarkup(); ?></div> <script src="path/to/react-bundle.js'"></script>
 <script src="path/to/components.js"></script> 
 <script><?= $rjs->getJS("#app"); ?></script>
  55. 55. talyssonoc/react-laravel
  56. 56. 
 <div>
 @react_component('Hello', $data )
 </div>
 Route::get('/foo', function() {
 return view('foo', ['data' => [ 'name' => 'world'] ]);
 });
  57. 57. Limenius/ReactBundle phpexecjs or node.js service (for Symfony)
  58. 58. node.js server Easier to install, update Standard environment for running react.js on the server Maintain separate server Fewer framework-level integrations v8js or node.js subprocess Write JS in PHP Complicated install and update process react-php-v8js library is experimental + + - + - - -
  59. 59. And remember, for any of these options: + Cache in production!
  60. 60. So what about all that JSX?
  61. 61. ReactDOM.render(<Greeting name="World"/>, el);
 Technically, this isn’t JavaScript
  62. 62. ReactDOM.render(<Greeting name="World"/>, el);
 Babel to the rescue! ReactDOM.render(React.createElement(Greeting, { name: "World" }), el);

  63. 63. Babel: Option 1 1. Transform JSX to JS on file change 2. Consume transformed bundle in V8js or node.js render server Use grunt, gulp, webpack, make, or a custom script. Or use your framework’s asset pipeline.
  64. 64. e.g., Using Laravel Elixir and Browserify elixir.config.js.browserify.transformers.push({
 name: 'babelify',
 options: {}
 });
  65. 65. Babel: Option 2 1. Use babel’s require hook 2. Also requires standalone build for production (only for dev, node.js) npm install babel-register require('babel-register');
  66. 66. …without JavaScript. Let’s talk functionality
  67. 67. • Use real links instead of buttons for navigation • Use forms with real submit actions for mutating data • Test without JavaScript!
  68. 68. this isn’t really a talk about React.js …or even PHP. But…
  69. 69. Let’s go a couple levels higher
  70. 70. What does MVC mean in a world of JavaScript frameworks?
  71. 71. View cohesion
  72. 72. Separate by concerns, not technologies
  73. 73. Architecture over individual technologies
  74. 74. Architecture over Technologies • React.js and PHP can work great together • But there are other options for client/server framework integration • reactjs/react-rails • laravel-angular (by @jadjoubran) • At Wayfair we wrote and use tungsten.js
  75. 75. Architecture over individual technologies
  76. 76. The library you choose is less important than how you choose to use it
  77. 77. Takeaways • React.js is most easily integrated in a PHP app if you’re ok with client-side only rendering • If you want server-side rendering, you have a few options too: node.js render server, or V8js • Focus primarily on architecture and design rather than just the choice of individual libraries
  78. 78. @AndrewRota Благодаря! Thank you!

×