Guide applies to: classic

Ext Direct with PHP and MySQL

Most web applications require the use of a client-side and a server-side. The client-side code cannot directly call server-side functions. Instead, the client sends requests, the server handles the requests, and then returns information to the client. Ext Direct allows developers to expose a list of server-side classes that can then be called directly from the client-side code, making the process of building applications much simpler. This allows you to streamline communication between client-side and server-side, resulting in less code, naming parity throughout your environment, and smarter XHR handling. Other benefits include:

  • Ext Direct is platform agnostic, so it works with any server-side language
  • Multiple Direct function calls are bundled into a single Ajax request (by default, all those sent in the first 10ms) so the server only has to send back a single response
  • Two “providers” offer multiple ways to communicate with the server:
    • Remoting Provider - Exposes server side functions to the client
    • Polling Provider - Allows sending events from server to the client via periodic polling

To put this into practice, let’s say you have a server-side class named Dog with a method named bark. When using Ext Direct, you can call Dog.bark() from within your JavaScript code.

To do this, you simply need to provide Ext Direct with a list of your server-side classes and methods and Ext Direct will then act as a proxy, giving you front-end access to your server-side environment.

Note: There are many variations in server side technology, but this guide uses the Remoting Provider along with PHP and MySQL.

Requirements

  • A server running PHP 5.3+
  • A server running MySQL 4.1+
  • Ext JS 6+
  • Sencha Cmd

Generate an Application

To begin, let’s generate an application using Sencha Cmd. Simply open your terminal, and issue the following command:

  1. sencha -sdk path/to/ext/ generate app -classic DirectApp ./DirectApp

You should now have a fully functional Classic application. We’ll work with the pre-configured views in this starter app to demonstrate connecting with Ext Direct.

Note: Your application should be available at http://localhost/DirectApp or http://localhost:1841/ if you’re using “sencha app watch”.

Direct Proxy

Our starter app already has a grid displaying names, emails, and phone numbers. However, it is using local data by way of a memory proxy. Let’s begin by opening the “app/store/Personnel.js” file. Once opened, remove the data object and change the proxy type to ‘direct’, and add a directFn of “QueryDatabase.getResults”. This is the function that we will create using PHP. The resulting code should look like this:

  1. Ext.define('DirectApp.store.Personnel', {
  2. extend: 'Ext.data.Store',
  3. alias: 'store.personnel',
  4. fields: [
  5. 'name', 'email', 'phone'
  6. ],
  7. proxy: {
  8. type: 'direct',
  9. directFn: "QueryDatabase.getResults"
  10. },
  11. autoLoad: true
  12. });

Refreshing your app should now result in an empty grid since we have not yet provided any data via our direct proxy.

Populating the Database

Let’s replace the data with something that already fits the name/email/phone fields. Use this SQL to create a “heroes” table:

  1. DROP TABLE IF EXISTS `heroes`;
  2. CREATE TABLE `heroes` (
  3. `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  4. `name` varchar(70) DEFAULT NULL,
  5. `email` varchar(255) DEFAULT NULL,
  6. `phone` varchar(10) DEFAULT NULL,
  7. PRIMARY KEY (`id`)
  8. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
  9. LOCK TABLES `heroes` WRITE;
  10. /*!40000 ALTER TABLE `heroes` DISABLE KEYS */;
  11. INSERT INTO `heroes` (`id`, `name`, `email`, `phone`)
  12. VALUES
  13. (1,'Thanos','[email protected]','5555555555'),
  14. (2,'Spider Man','[email protected]','2125555555'),
  15. (3,'Daredevil','[email protected]','2125555555'),
  16. (4,'The Maker','[email protected]','2125555555'),
  17. (5,'Rocket','[email protected]','5555555555'),
  18. (6,'Galactus','[email protected]','5555555555'),
  19. (7,'Silver Surfer','[email protected]','5555555555'),
  20. (8,'Hulk','[email protected]','2125555555'),
  21. (9,'Squirrel Girl','[email protected]','2125555555'),
  22. (10,'Thor','[email protected]','5555555555');
  23. /*!40000 ALTER TABLE `heroes` ENABLE KEYS */;
  24. UNLOCK TABLES;

You should now have a MySQL table populated with 10 records that we’ll display in our grid. Now that we have data, let’s create a connection.

Creating the Query

In the root directory of our app, create a folder called ‘php’ followed by another one inside it called “classes”. Within “classes” create a file called “QueryDatabase.php”.

We’ll be utilizing PHP’s MySQLi extension which works with MySQL 4.1.3 and above (any version released after mid-2004 will be fine).

We won’t delve too far into the PHP code. Most of it should be pretty straight forward for anyone who has queried MySQL via PHP. We’re defining a new class, declaring some variables, creating a connector, and making a function that gets results from the database.

  1. <?php
  2. class QueryDatabase {
  3. private $_db;
  4. protected $_result;
  5. public $results;
  6. public function __construct() {
  7. $this->_db = new mysqli('host', 'username' ,'password', 'database');
  8. $_db = $this->_db;
  9. if ($_db->connect_error) {
  10. die('Connection Error: ' . $_db->connect_error);
  11. }
  12. return $_db;
  13. }
  14. public function getResults($params) {
  15. $_db = $this->_db;
  16. $_result = $_db->query("SELECT name,email,phone FROM heroes") or
  17. die('Connection Error: ' . $_db->connect_error);
  18. $results = array();
  19. while ($row = $_result->fetch_assoc()) {
  20. array_push($results, $row);
  21. }
  22. $this->_db->close();
  23. return $results;
  24. }
  25. }

To recap, we declared some variables at the top of the class and and made two functions that will help us as we expand our application.

The first function (__construct) creates the database connection instance. If it fails to connect, it will provide a detailed error message.

The second function (getResults) uses the first function to open a connection and queries the database for all of the column fields. We then push all of the results into an array called $results by way of a while statement. Finally, we close the connection to the database and return the results.

Note: Replace hostname, password, and database with your own credentials.

Config

Let’s go up a level to the “php” directory and create a new file called “config.php” and add the following code:

  1. <?php
  2. function get_extdirect_api() {
  3. $API = array(
  4. 'QueryDatabase' => array(
  5. 'methods' => array(
  6. 'getResults' => array(
  7. 'len' => 1
  8. )
  9. )
  10. )
  11. );
  12. return $API;
  13. }

This exposes the functions we want to be made available to our Ext application to call the server. For now, we only need to add the ‘getResults’ method we created above.

That’s all there is to our config.php file for now.

Router

Next, we’ll need a router to make sure the correct methods are called. The router is where the calls from Ext Direct get routed to the correct class using a Remote Procedure Call (RPC).

While still in the “php” directory, let’s create another file called “router.php” and add the following code.

  1. <?php
  2. require('config.php');
  3. class BogusAction {
  4. public $action;
  5. public $method;
  6. public $data;
  7. public $tid;
  8. }
  9. $isForm = false;
  10. $isUpload = false;
  11. if (isset($HTTP_RAW_POST_DATA)) {
  12. header('Content-Type: text/javascript');
  13. $data = json_decode($HTTP_RAW_POST_DATA);
  14. }
  15. else if(isset($_POST['extAction'])){ // form post
  16. $isForm = true;
  17. $isUpload = $_POST['extUpload'] == 'true';
  18. $data = new BogusAction();
  19. $data->action = $_POST['extAction'];
  20. $data->method = $_POST['extMethod'];
  21. $data->tid = isset($_POST['extTID']) ? $_POST['extTID'] : null;
  22. $data->data = array($_POST, $_FILES);
  23. }
  24. else {
  25. die('Invalid request.');
  26. }
  27. function doRpc($cdata){
  28. $API = get_extdirect_api('router');
  29. try {
  30. if (!isset($API[$cdata->action])) {
  31. throw new Exception('Call to undefined action: ' . $cdata->action);
  32. }
  33. $action = $cdata->action;
  34. $a = $API[$action];
  35. $method = $cdata->method;
  36. $mdef = $a['methods'][$method];
  37. if (!$mdef){
  38. throw new Exception("Call to undefined method: $method " .
  39. "in action $action");
  40. }
  41. $r = array(
  42. 'type'=>'rpc',
  43. 'tid'=>$cdata->tid,
  44. 'action'=>$action,
  45. 'method'=>$method
  46. );
  47. require_once("classes/$action.php");
  48. $o = new $action();
  49. if (isset($mdef['len'])) {
  50. $params = isset($cdata->data) && is_array($cdata->data) ? $cdata->data : array();
  51. }
  52. else {
  53. $params = array($cdata->data);
  54. }
  55. array_push($params, $cdata->metadata);
  56. $r['result'] = call_user_func_array(array($o, $method), $params);
  57. }
  58. catch(Exception $e){
  59. $r['type'] = 'exception';
  60. $r['message'] = $e->getMessage();
  61. $r['where'] = $e->getTraceAsString();
  62. }
  63. return $r;
  64. }
  65. $response = null;
  66. if (is_array($data)) {
  67. $response = array();
  68. foreach($data as $d){
  69. $response[] = doRpc($d);
  70. }
  71. }
  72. else{
  73. $response = doRpc($data);
  74. }
  75. if ($isForm && $isUpload){
  76. echo '<html><body><textarea>';
  77. echo json_encode($response);
  78. echo '</textarea></body></html>';
  79. }
  80. else{
  81. echo json_encode($response);
  82. }

This code will require the config file containing the methods we defined for API exposure. We also add a doRpc function that will provide important information about our data and responses from the server.

Note: Slightly more advanced version of router.php (and api.php in the next section) can be found within the “ext/examples/kitchensink/data/direct” folder within the SDK.

API

Finally, let’s create a file called ‘api.php’ and populate it with the following code:

  1. <?php
  2. require('config.php');
  3. header('Content-Type: text/javascript');
  4. // convert API config to Ext Direct spec
  5. $API = get_extdirect_api();
  6. $actions = array();
  7. foreach ($API as $aname=>&$a) {
  8. $methods = array();
  9. foreach ($a['methods'] as $mname=>&$m) {
  10. if (isset($m['len'])) {
  11. $md = array(
  12. 'name'=>$mname,
  13. 'len'=>$m['len']
  14. );
  15. } else {
  16. $md = array(
  17. 'name'=>$mname,
  18. 'params'=>$m['params']
  19. );
  20. }
  21. if (isset($m['formHandler']) && $m['formHandler']) {
  22. $md['formHandler'] = true;
  23. }
  24. $methods[] = $md;
  25. }
  26. $actions[$aname] = $methods;
  27. }
  28. $cfg = array(
  29. 'url'=>'php/router.php',
  30. 'type'=>'remoting',
  31. 'actions'=>$actions
  32. );
  33. echo 'var Ext = Ext || {}; Ext.REMOTING_API = ';
  34. echo json_encode($cfg);
  35. echo ';';

This file uses the “config.php” file we made earlier and sets the output header to JavaScript. This ensures that the browser will interpret any output as JavaScript. It then proceeds to turn our config and router PHP files into JSON so the right method is called when Ext Direct calls it.

Again, the content of “api.php” can be found within the “ext/examples/kitchensink/data/direct” folder within the SDK.

Updating app.json

Next, let’s tell Cmd about “api.php”, the application’s “entry point” to our Direct. The best way to communicate our needs to Cmd is by way of “app.json’s” javascript array. Open “app.json” and find the JS array. Then add “api.php” as a remote inclusion. The resulting array should look like this:

  1. "js": [
  2. {
  3. "path": "php/api.php",
  4. "remote": true
  5. },
  6. {
  7. "path": "app.js",
  8. "bundle": true
  9. }
  10. ],

If you are not using Cmd to build your application, you can add “api.php” to a script tag in your application’s “index.html” file. Just make sure that “api.php” line comes before the “app.js” line.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  5. <title>App Title</title>
  6. <!--Ext JS-->
  7. <link rel="stylesheet" type="text/css" href="resources/css/ext-all.css">
  8. <script src="extjs/ext-all-debug.js"></script>
  9. <!--Application JS→
  10. <script src="php/api.php"></script>
  11. <script src="app.js"></script>
  12. </head>
  13. <body>
  14. </body>
  15. </html>

Because we’re using the HTML5 document type, we’re allowed to omit the type in a script tag, it assumes that all <script> tags will be JavaScript which helps cut down our bytes.

Provider

We’ve made it to our final step to populate the grid with results! We now need to add a provider to the direct manager. As we discussed earlier, there are two providers in the framework, but we’ll be using the remoting api for this particular project. Open your “Application.js” file and add the provider to the direct manager within the launch function. It should like this:

  1. launch: function () {
  2. Ext.direct.Manager.addProvider(Ext.REMOTING_API);
  3. },

Note: “Ext.REMOTING_API” is the name of the variable that was created by the JavaScript code printed in “api.php”. You can use any variable name you like but it should be the same in both places.

Conclusion

Refreshing your application should now display our new grid results. As you can see, there’s a little bit of setup involved, but once complete, adding new methods is simply a matter of writing them and adding them to your config file. You then have direct access to your server side methods, which streamlines your code and a whole lot more!