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 4+ (this example uses 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:

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:

Ext.define('DirectApp.store.Personnel', {
    extend: 'Ext.data.Store',

    alias: 'store.personnel',

    fields: [
        'name', 'email', 'phone'
    ],

    proxy: {
        type: 'direct',
        directFn: "QueryDatabase.getResults"
    },

    autoLoad: true
 });

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:

DROP TABLE IF EXISTS `heroes`;

 CREATE TABLE `heroes` (
   `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
   `name` varchar(70) DEFAULT NULL,
   `email` varchar(255) DEFAULT NULL,
   `phone` varchar(10) DEFAULT NULL,
   PRIMARY KEY (`id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 LOCK TABLES `heroes` WRITE;
 /*!40000 ALTER TABLE `heroes` DISABLE KEYS */;

 INSERT INTO `heroes` (`id`, `name`, `email`, `phone`)
 VALUES
      (1,'Thanos','thanos@infgauntlet.com','5555555555'),
      (2,'Spider Man','peter.parker@thebugle.net','2125555555'),
      (3,'Daredevil','matt.murdock@nelsonandmurdock.org','2125555555'),
      (4,'The Maker','reed.richards@therealreedrichards.net','2125555555'),
      (5,'Rocket','rocket@starlordstinks.com','5555555555'),
      (6,'Galactus','galactus@worldeater.com','5555555555'),
      (7,'Silver Surfer','norrin.radd@zenn-la.gov','5555555555'),
      (8,'Hulk','bruce.banner@hulkout.org','2125555555'),
      (9,'Squirrel Girl','doreen.green@nannyservices.net','2125555555'),
      (10,'Thor','thor@odinson.gov','5555555555');

 /*!40000 ALTER TABLE `heroes` ENABLE KEYS */;
 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.

<?php

 class QueryDatabase {

    private $_db;
    protected $_result;
    public $results;

    public function __construct() {
        $this->_db = new mysqli('host', 'username' ,'password', 'database');

        $_db = $this->_db;

        if ($_db->connect_error) {
            die('Connection Error: ' . $_db->connect_error);
        }

        return $_db;
    }

    public function getResults($params) {
        $_db = $this->_db;

        $_result = $_db->query("SELECT name,email,phone FROM heroes") or
                   die('Connection Error: ' . $_db->connect_error);

        $results = array();

        while ($row = $_result->fetch_assoc()) {
            array_push($results, $row);
        }

        $this->_db->close();

        return $results;
    }

 }

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:

<?php

 function get_extdirect_api() {

    $API = array(
        'QueryDatabase' => array(
            'methods' => array(
                'getResults' => array(
                    'len' => 1
                )
            )
        )
    );

    return $API;
 }

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.

<?php
 require('config.php');

 class BogusAction {
    public $action;
    public $method;
    public $data;
    public $tid;
 }

 $isForm = false;
 $isUpload = false;

 if (isset($HTTP_RAW_POST_DATA)) {
    header('Content-Type: text/javascript');
    $data = json_decode($HTTP_RAW_POST_DATA);
 }
 else if(isset($_POST['extAction'])){ // form post
    $isForm = true;
    $isUpload = $_POST['extUpload'] == 'true';
    $data = new BogusAction();
    $data->action = $_POST['extAction'];
    $data->method = $_POST['extMethod'];
    $data->tid = isset($_POST['extTID']) ? $_POST['extTID'] : null;
    $data->data = array($_POST, $_FILES);
 }
 else {
    die('Invalid request.');
 }

 function doRpc($cdata){
    $API = get_extdirect_api('router');

    try {
        if (!isset($API[$cdata->action])) {
            throw new Exception('Call to undefined action: ' . $cdata->action);
        }

        $action = $cdata->action;
        $a = $API[$action];

        $method = $cdata->method;
        $mdef = $a['methods'][$method];

        if (!$mdef){
            throw new Exception("Call to undefined method: $method " .
                                "in action $action");
        }

        $r = array(
            'type'=>'rpc',
            'tid'=>$cdata->tid,
            'action'=>$action,
            'method'=>$method
        );

        require_once("classes/$action.php");
        $o = new $action();

        if (isset($mdef['len'])) {
            $params = isset($cdata->data) && is_array($cdata->data) ? $cdata->data : array();
        }
 else {
            $params = array($cdata->data);
        }

        array_push($params, $cdata->metadata);

        $r['result'] = call_user_func_array(array($o, $method), $params);
    }

    catch(Exception $e){
        $r['type'] = 'exception';
        $r['message'] = $e->getMessage();
        $r['where'] = $e->getTraceAsString();
    }

    return $r;
 }

 $response = null;

 if (is_array($data)) {
    $response = array();
    foreach($data as $d){
        $response[] = doRpc($d);
    }
 }
 else{
    $response = doRpc($data);
 }

 if ($isForm && $isUpload){
    echo '<html><body><textarea>';
    echo json_encode($response);
    echo '</textarea></body></html>';
 }
 else{
    echo json_encode($response);
 }

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:

<?php
 require('config.php');
 header('Content-Type: text/javascript');

 // convert API config to Ext Direct spec
 $API = get_extdirect_api();
 $actions = array();

 foreach ($API as $aname=>&$a) {
    $methods = array();
    foreach ($a['methods'] as $mname=>&$m) {
        if (isset($m['len'])) {
            $md = array(
                'name'=>$mname,
                'len'=>$m['len']
            );
        } else {
            $md = array(
                'name'=>$mname,
                'params'=>$m['params']
            );
        }
        if (isset($m['formHandler']) && $m['formHandler']) {
            $md['formHandler'] = true;
        }
        $methods[] = $md;
    }
    $actions[$aname] = $methods;
 }

 $cfg = array(
    'url'=>'php/router.php',
    'type'=>'remoting',
    'actions'=>$actions
 );

 echo 'var Ext = Ext || {}; Ext.REMOTING_API = ';

 echo json_encode($cfg);
 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:

"js": [
    {
        "path": "php/api.php",
        "remote": true
    },
    {
        "path": "app.js",
        "bundle": true
    }
 ],

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.

<!DOCTYPE html>
 <html>
 <head>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
     <title>App Title</title>
     <!--Ext JS-->
     <link rel="stylesheet" type="text/css" href="resources/css/ext-all.css">
     <script src="extjs/ext-all-debug.js"></script>
     <!--Application JS→
     <script src="php/api.php"></script>
     <script src="app.js"></script>
 </head>
 <body>
 </body>
 </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:

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

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!

Last updated