Zend Framework 2 JSON-RPC

Calling a PHP Method from JavaScript

Getting data from the backend database to the browser can be a pain.  Using RESTful interfaces is great but basically requires you to hand craft every call.  What if you could just call your PHP methods directly from JavaScript without having to worry about how that call happened?  With Zend Framework 2 JSON-RPC and a little bit of glue code you can.

Zend Framework 2 JSON-RPC

REST and JSON-RPC solve the same problem, exchanging data between two system.  One difference between the two is in the level of code automation that takes place.  While connecting a RESTful service to a PHP model can be a tedious and time consuming experience, connecting that same PHP model to JavaScrip using JSON-RPC in ZF2 can be done in just a few lines of code.

Hello World AJAX via JSON-RPC

Lets start with a clean copy of the ZF2 Skeleton:

If you need help pulling a copy of the ZF2 Skeleton app, check out http://framework.zend.com/manual/current/en/user-guide/skeleton-application.html.

Make sure you see the Welcome screen in your browser.

Screen Shot 2015-06-24 at 2.15.42 PM

 

Next grab a copy of jquery.zend.jsonrpc.js (258 downloads)  and put it into the (web root)/public/js folder.  This is the glue code that will connect JavaScript to a PHP Class.

The View file

Put the following into a view file in /module/Application/view/application/index/jsondemo.phtml.

 

The Controller

Add to the /module/Application/src/Application/Controller/IndexController.php so it look like:

 

The Model

Finally put the following in /module/Application/src/Application/Model/Hello.php

 

The Demo

Opening up the browser to http://localhost/application/index/jsondemo should bring up the demo page.

JSON-RPC Demo Page

JSON-RPC Demo Page

Clicking the “Test” button will call the HelloWorld() method from the Hello PHP Class.

JSON-RPC Demo Test

JSON-RPC Demo Test

The Power

From this trivial example the power of this technique may not be readily apparent.  From this point adding more calls between JavaScript and PHP can be done as quickly as you can write the PHP methods and JavaScript calls.  Pass structures of arrays and change the library to asynchronous and you will have a powerful way to integrate PHP and JavaScript.

The Code

Download the code  jsonrpc.zip (439 downloads) .

 

Leave a Reply