Any Javascript and PHP AJAX Interface generation suggestions, like thrift? - php

I am basically looking for Apache Thrift, but to talk between JavaScript over Ajax and PHP.
I know Thirft generates both, but to my knowledge the JavaScript code must talk over JSONProtocol, of which the protocol isn't yet wrote in PHP.
Are there any other alternatives that can suggested?
If you are unfamiliar with Thrift, this is a simple(ish) definition of what i need:
Consider this as the generic interface definition language (IDL), where I setup a User object, an AuthenticationResult result object, and method named UserCommands.Authenticate();
struct User {
1: number id,
2: string firstName,
3: string lastName
}
struct AuthenticationResult {
1: number currentTime,
2: User user
}
service UserCommands {
AuthenticationResult Authenticate(1:string username, 2:string password)
}
I run a program or something, it creates JS and PHP libraries based on the above.
Then, in JS, I could call (with helpful typehinting).
var myAuthResult = UserCommands.Authenticate('myUser', 'myPass');
alert ("My first name is : " + myAuthResult.user.firstName);
And in PHP, I would setup a method in a UserCommands class like this:
function Authenticate($username, $password) {
$myUser = new User();
$myUser->firstName = "Fred";
$myUser->lastName = "Thompson";
$myAuthResult = new AuthenticationResult ();
$myAuthResult->currentTime = date("U");
$myAuthResult->user = $myUser;
return $myAuthResult;
}
The benefits are that PHP can return native objects and JS can expect to receive its own native objects.
Type hinting for available methods are provided through out, with expected params and return results.
Any thoughts would be appreciated!

First of all, there're json_encode and json_decode functions in php.
Secondly, there's a serialize/unserialize for native php types
I don't understand, though, which you mean under "... of which the protocol isn't yet wrote in PHP."
Also, there's a Haxe langauge, which can be "compiled" into both PHP and JavaScript (and some other languages)

Related

How to properly call a class while providing error reporting at the class-caller level

I am writing fresh code, as part of refactoring an older legacy codebase.
Specifically, I am writing a Device class that will be used to compute various specifications of a device.
Device class depends on device's model number and particle count and I can call it as $device = new Device($modelNumber, $particleCount);
Problem: since this class will go into existing legacy code, I have no direct influence on if this class will be called properly. For Device to work, it needs to have correct model number and correct particle count. If it does not receive the proper configuration data, internally device will not be initialized, and the class will not work. I think that I need to find a way to let the caller know that there was an error, in case an invalid configuration data was supplied. How do I structure this to be in line with object oriented principles?
Or, alternatively, do I need to concern myself with this? I think there is a principle that if you supply garbage, you get garbage back, aka my class only needs to work properly with proper data. If improper data is supplied, it can bake a cake instead, or do nothing (and possibly fail silently). Well, I am not sure if this principle will be great. I do need something to complain if supplied configuration data is bad.
Here is some code of what I am thinking:
$device = new Device($x, $y);
$device->getData();
The above will fail or produce bad or no data if $x or $y are outside of device specs. I don't know how to handle this failure. I also want to assume that $device is valid when I call getData() method, and I can't make that assumption.
or
$device = new Device($x, $y);
if ($device->isValid())
$device->getData();
else
blow_up("invalid device configuration supplied");
The above is better, but the caller has to now they are to call isValid() function. This also "waters down" my class. It has to do two things: 1) create device, 2) verify device configuration is valid.
I can create a DeviceChecker class that deals with configuration vefication. And maybe that's a solution. It bothers me a little that DeviceChecker will have to contain some part of the logic that is already in Device class.
Questions
what problem am I trying to solve here? Am I actually trying to design an error handling system in addition to my "simple class" issue? I think I probably am... Well, I don't have the luxury of doing this at the moment (legacy code base is huge). Is there anything I can do now that is perhaps localized to the pieces of code I touch? That something is what I am looking for with this question.
I think you need to use below code to verify your passed arguments in construct
class Device {
public function __constructor($modelNumber, $particleCount) {
if(!$this->isValid($modelNumber, $particleCount) {
return false; //or return any error
}
}
}
This will check the passed params are valid or not and create object based on that only, otherwise return false or any error.

call RPGLE program from SQL within PHP / Zend Framework

We have an AS400 RPGLE program created within the library LMTLIB, which is called ARTEST.
It has a single numeric inout parameter, which just returns 2
$myVar = "1";
$db = Zend_Registry::get('config')->resources->multidb->as400;
$abstractAdapter = new Zend_Db_Adapter_Db2($db);
//Gives the message "Invalid bind-variable position 'myVar'"
$sql = 'CALL QSYS.QCMDEXC(\'CALL LMTLIB.ARTEST PARM(?)\', 0000000026.00000)';
//Gives the message "Token PARM was not valid. Valid tokens: ( INTO USING. SQLCODE=-104"
$sql = 'CALL LMTLIB.ARTEST PARM(?)';
//Gives the message "ARTEST in LMTLIB type *N not found. SQLCODE=-204"
$sql = 'CALL LMTLIB.ARTEST (?)';
$stmt = new Zend_Db_Statement_Db2($abstractAdapter, $sql);
$stmt->bindParam('myVar', $myVar, 4, 1);
$stmt->execute();
Now, i can kind-of understand why the third SQL statement would fail with the "not found" message... because it is not a table / file, but rather an RPGLE program.
The thing thats irritating, is that if i remove the (?), and simply put in (1)... the SQL call appears to be successful, and the RPGLE program shows it had been called. However, I'm then not able to see what the response from the program was.
Thanks in advance for any help!
Generally, the database manager uses the CALL statement to invoke a stored procedure. When it does that, it looks for a stored proc whose parameter signature matches the signature of the CALL.
If there's no stored proc with that name and signature, the database manager tries to call a program. Again, there's a parameter matching process that happens.
http://publib.boulder.ibm.com/infocenter/iseries/v5r4/topic/db2/rbafzmstcallsta.htm
I suggest creating a stored procedure so you can get the parameters matched properly.
IBM RPGLE can interface with the Zend framework through webservice calls.
Scott Klement goes over some of the basics of this here.
Depending on your application, this may be the best way to interface with RPG code. Webservices can be made to call many RPG programs and iSeries tables, and return a catered result set. Zend would see this the same as any other RESTful call, which could be handled by your models.

OO PHP + Ajax without framework

I'm going to write a booking website using php and ajax and I really can't figure how to mix these two tools with a strict object oriented design.
I was used to make a call using ajax to a php web page that returns the right set of values (string, xml, json) in a procedural way.
With object oriented programming how is it supposed to work?
The simplest solution that i can think is to call through ajax a php page that should only instantiate a new object of the right class and then make an echo on the result of a simple call with the data received but this doesn't look very oo...
For example to implement the register function I should make an ajax call to a register.php web page that, in turn, will instantiate a new Registration object r and then simply calls r.register() with the right data.
Is there a better solution to this problem?
I want specify that I can't use any php framework because it's a didactic project and I have this rule that I should respect.
Another specification: I've read a lot of tutorials that describe how to write your own mvc framework but doing this seems to be an overkill for my problem.
Thank you for your help, every idea will be appreciated.
As you already said you don't really need a PHP framework and don't need to build your own MVC implementation
(especially if you are e.g. working with JSON or XML).
Basically you are pretty free on how to do your OO model, so your idea is not necessarily wrong.
Some OO anti patterns I have seen people using in PHP:
Use global variables in classes
Create classes without member
variables resulting in method calls
being the same as in a produral style
Directly accessing $_GET, $_POST etc.
in a class
Echoing html output (imho this should
be done in view templates)
An example for what you might want to do for the registering process processing some $_POST variables
and returning a JSON success message:
<?php
class Registration
{
private $_data;
public function __construct($registrationdata)
{
$this->_data = $registrationdata;
}
public function validate()
{
// ...
}
public function register()
{
// ...
if($this->validate())
return array("registered" => true, "username" => $this->_data["username"],
"message" => "Thank you for registering");
else
return array("registered" => false, "username" => $this->_data["username"],
"message" => "Duplicate username");
}
}
$reg = new Registration($_POST);
echo json_encode($reg->register());
?>
There is no reason to create any classes if all you are doing is calling a couple of unrelated stateless php functions.

Calling web service (SOAP) with PHP involving enums

I wish to call a web service, using SOAP, from PHP (using the included SOAP extension). The web service in question is http://www.webservicex.net/CurrencyConvertor.asmx
Now the Currency type is an enum, and I cannot figure out how to work with these in PHP in order to be able to call the 'ConversionRate' function. I know I have to do something with a class map, but I can only find limited and unhelpful information on this topic. Can anyone help? A working example maybe?
Thanks!!!!
The enum here only defines legitimate values, that is your data type is actually a string of one of those values.
Here's some psuedo-code to get you on your way:
$from_currency = "AFA";
$to_current = "ALL";
$soap_handler->ConversionRate($from_currency, $to_currency);
$exchange_rate = $soap_handler->response();

Best Practice for returning cross-site JSON response

I'm currently working on a small application that works like this:
When the user clicks a link, an Ajax GET request is fired.
The request hits a server-side PHP script.
The script, which requests information for another domain, retrieves a JSON feed.
The feed is then echoed back to the client for parsing.
I'm not really a PHP developer, so I am looking for some best practices with respect to cross-domain requests. I'm currently using file_get_contents() to retrieve the JSON feed and, although it's functional, it seems like a weak solution.
Does the PHP script do anything other than simply call the other server? Do you have control over what the other server returns? If the answers are No and Yes, you could look into JSONP.
You might want to abstract the retrieval process in PHP with an interface so you can swap out implementations if you need too. Here is a naive example:
interface CrossSiteLoader
{
public function loadURL($url);
}
class SimpleLoader implements CrossSiteLoader
{
public function loadURL($url)
{
return file_get_contents($url);
}
}
Comes in handy if you need to test locally with your own data because you can use a test implementation:
public ArrayLoader implements CrossSiteLoader
{
public function loadURL($url)
{
return json_encode(array('var1' => 'value1', 'var2' => 'value2'));
}
}
or if you just want to change from file_get_contents to something like curl

Categories