Handling DataSnap (REST) server methods through PHP
Create PHP applications to connect to DataSnap REST servers is relatively simple since the RadPHP includes a wizard that generates the proxy classes in PHP, but as PHP is a dynamic language and is not strongly typed, it opens the possibility for errors when we execute the server methods, in addition to that REST calls always returns a JSON object, but if you are aware how REST, JSON and DataSnap works it became easy to manage.
Consider the following scenario where you have an authentication method that returns TRUE or FALSE, of course you must be thinking that in case of error the method will always return false, this is not necessarily true and I’ll explain next.
Assuming you have generated the proxy class in PHP through RadPHP IDE, you have what you need to execute the DataSnap business logic from PHP code, when the server method is executed from REST server it will always return an JSON object.
The RadPHP proxy generator wizard will create a datamodule which containing the DSRestConnection component, this component has the necessarily information to connect to the server, like: Host, Port, Username and Password.
The following code execute the server method TUser.isValidUser having username and password as parameter, if the server method returns an instance of DSObject it means the method was executed successfully and it will have a DSObject->result property, in this case TRUE or FALSE, in case the method fails for some reason or raise an EXCEPTION DSObject will not be returned and you will have to check the property ERROR to get the error message.
type global $ClientModuleDataModule1; $conninfo = $ClientModuleDataModule1->DSRestConnection1->ConnectionInfo; $user = new TUser($conninfo); $valid = $user->IsValidUser($this->edUserName->Text, $this->edPassword->Text); if($valid instanceof DSObject) { if($valid->result) { setcookie('loginid', $this->edUserName->Text); redirect("Main.php"); } else { $this->Button1->Caption = "Username/Password invalid"; } } else { $this->Button1->Caption = $valid->error; }
In the examples of RAD Studio XE available at sourceforge you can download the full PHP code used on this post, as well the Delphi DataSnap server, download here.
Trackbacks & Pingbacks
[…] This post was mentioned on Twitter by Embarcadero Tech. Embarcadero Tech said: Handling DataSnap (REST) server methods through PHP: Create PHP applications to connect to DataSnap REST servers… http://bit.ly/howylu […]
Leave a Reply
Want to join the discussion?Feel free to contribute!