/ json

JsonRPC 2 PHP: a php jsonRPC2 Server

note: This post is from 2012. It was imported from wordpress for nostalgic reasons.

Some time ago I wanted a standard for all my ajax RPC requests for my PHP projects. After searching the web, I found the JsonRPC2 standard (http://www.jsonrpc.org/spec.html)

To my knowledge there wasn’t a good client-server library available for jsonRPC2 for use with php and javascript. So I wrote one. You can find the project here :https://github.com/subutux/json-rpc2php

What it does

The server version (in PHP) makes your defined classes accessible trough the JsonRPC2 protocol. (See the README.md in the git) Simply define the classes you want access to and you’re ready to go! It’s quite simple to use and perfect to implement in any class-based php project.

The javascript client

This was a hard one. I wanted it to be as simple as it could:

  • Define the endpoint (api url) as follows : rpc = new jsonrpc2client(‘http://localhost/api.php’)
  • use the functions of the classes as native javascript methods: rpc.myClass.ping(‘testing one 2 three’)

After a lot of debugging, I succeeded in my mission. I’m really proud of what I’ve written in the client. It’s simple, easy to use.

On a side note: There is one thing i’m not so fond about. the async behavior of the initial creating of the javascript class. but that’s how javascript is build. I’ve had to make a main callback for the init of the rpc, (see the README.md) because, while getting the rpc methods and classes & building the functions, it could happen that a function is called (ex. rpc.myClass.ping) before it was created. Therefore, iv’e added a callback. This callback is executed when all the methods are created.

The PHP Client

It works exactly the same as the javascript version except for 2 things:

  1. Every class init of jsonrpc2client can contain only one rpc class
  2. No problems with async

1. isn’t exactly a problem. It’s quite excellent! It works exacly as simple php classes behave. (again, check the README.md for example). You just define a new jsonrpc2client with 2 parameters: the endpoint (api url), and the class to connect to.

The Python client

This one works exactly as the php client. It uses the __getattr__ magic python function to call a method of a class.

So, I hope you enjoy the libs I’ve written. If you do, it would be awesome to buy me a beer !.