Easiest RPC client method in PHP - php

I've been asked to help a friend's company to bring up a web application. I have very limited time and I reluctantly accepted the request, at one condition. As most of the logic goes on in the back-end, I suggested that I would finish the complete back-end only, allowing a front-end developer to simply interface with my backend.
I plan to do the back-end in Java EE or Python (with Pylons). It does not really matter at this point. I plan to have my back-end completely ready and unit-tested, so that my input will hardly be needed after my work is done.
I know they have a PHP programmer, but as far as I could tell he is a real rookie. I want him to basically interface with my backend's services in the easiest possible way, with no way of him "stuffing" it up. It's basically a CRUD-only application.
I could implement the backend as accessible through a webservice such as XML-RPC or SOAP. Even a RESTful API could be possible.
However, my main objective is to make something that complete "noob" PHP programmer can easily interface with without getting confused. Preferably I do not even want to talk to him because I generally have an extremely busy schedule, and doing "support calls" is not something I am willing to do. Which approach should I choose? I would welcome any suggestions and inputs!

I would personally choose a REST API, probably with a JSON response. SOAP and XML can be a bit heavy-handed for simple services, and even the most novice web developer understands the concept of accessing a basic URL, even if they don't grok the overall concept of REST. There are myriads of ways to work with URLs in PHP, so I'm sure they'd be able to come up with something, even if it was a hack job instead of a nice client package.
I would also likely choose JSON encoding and decoding, as it's generally fairly straightforward, while XML parsing can be a bit more daunting.
I would also write up at least some basic documentation on the service, no matter what formats you choose. Otherwise there's no way you will escape support calls. Your target consumer must have a reference of the remote actions available to him, or a method to discover those actions. It would probably take you 10 minutes to whip up some example code when it's ready, and those 10 minutes could save you a lot of emailing.

Definitly go with a rest-like implementation, and return query string formatted output.
Just remember that php will turn array like variables into an array on the php side.
Take a query string for your parameters
Input:
p1=v1&p2=v2....
Output:
output1=var1&output[0]=var2;output[2]=var3
Accessing this in php is then a simple as
<?
$request['myparam1'] = param;
...
$webService ="http://path.to.service?".http_build_query($request);
parse_str(file_get_contents($webService),$response);
// response is now an array with you response parameters in it
// $response['responseParam1'], reponse['responseParam1'] etc
?>
parse_str
http_build_query

Been there, done that.
Backend in Django, frontend in PHP by a 'we do pages' contractor. i whipped up a REST-like API using JSON, provided them with a couple of 5-line PHP functions to access my service as a key-value store.
After a couple of false starts (where they tried a contrived and redirections scheme instead of using the functions i sent them), they got it and everything went smoothly after that.

Related

Taking the good parts of both Spring and php in a common server environment

What I would propose would probably sound strange, but I have my reasons for it.
For a long time, we've had this Spring based API, which originated as an abstract set of REST services for CRUD functionality. With time however, we started building business and presentation layers on top until we reached a state of a dead end. Do not get me wrong, Spring/Hibernate are great frameworks, and being built on top of the JVM has its definite advantages, including performance over other web technologies, such as PHP. Compared to PHP, it gives us a much deeper way of controlling aspects such as transactioning, multithreading, dealing with byte data, control over native C++ applications, using JNI, etc.
Where the stack clearly hits a hard wall, is where the requirements get changed most often, namely the business and presentation layers. Turning the applciation into a modern, user-centered social applciation, we've experienced the toughest challenge in out careers. Java EE presentation technologies are tough to work with. Also, changing the business requirements became a tremendously long cycling because of the traditional hurdles in building testing and deploying massive Java applications.
It also felt like for a large part, we are trying to reinvent the wheel. In the PHP world, so many projects exist already, which give you a complete management system, agnostic to any kind of backend system (mapping hooks to REST/SOAP endpoints) . Many of them have all these functionalities ready, allow for admin-friendly change of scenarious, and rules, have templating, etc. Plus, being PHP based means absolutely no time wasted in building and deploying. Write the change, test, asert that it works, and switch.
Our idea now is to find a way to move the business and presentation layers in such a kind of front-server PHP-based application, and leave the pure backend stuff to Spring/Hibernate. We have a few concerns though, coming from our relative inexperience with Spring.
If we implement the business methods using PHP methods, how do we keep transactional security? I mean if a business method has to make three separate HTTP requests to the JAVA, how can we guarantee that they will all be executed in the same transaction, DB-wise?
Is there a way to use proxies or promise objects between both systems? For instance, if the PHP business method needs to call a Spring search method get a collection of objects from the database, and then pass it on to another spring method, this will mean that teh whole collection will have to be sent back and forth. Perhaps, one could store it in a session object on the JAVA side, and simply sent an empty proxy back to the frontend, which the frontend can bass back to another jav method.
A lot of our Spring based functionailities rely on a structure of plugins, using Spring events. How can we make so that our frontend server also gets notified on every ackend event that happens.
I have two ideas here: a post-processing-filter that simply makes a POST request to a controller on the frontend server, using some naming convention.
or ... using some kind of a message queue, such as JMS or RabbitMQ, or why not even something like Reddis, where one can watch data for changes
Anyone who has done that before? Is this a good idea in general? Any suggestions how to resolve the aforementioned issues?
This is not what you asked, but I think it's worth saying that some of the problems you are experiencing with Java are problems that most experienced Java developers faced some day, and most have found some solution. For instance, you can use Arquillian to do a "faster" TDD in Java. And you can use JRebel to do a "code-and-refresh" approach, like in PHP. Modern IDEs also helps in refactoring, something that helps in the "requirements change" scenario.
Granted, the presentation part is still a big problem with Java. I personally don't like JSF, and (to me), most of the other presentation technologies are either non-intuitive or they are cumbersome.
I would say that this is the reason why a lot of Java developers are becoming adopters of HTML5 and Javascript (backbone.js, underscore.js, jquery, ...) for the frontend, with REST in the backend. There's no need to have PHP in the middle.
I'm afraid I cannot answer your other questions, but perhaps a good start would be to see if PHP could be run from inside a Java EE container? I know this works for Ruby and Python apps, as JRuby and Jython would take care of the bridge between the two world.
Largely what you are trying to do is what we call: SOFEA
In this case PHP is your frontend and Java is your service layer.
Concern 1
Transactions over traditional REST or WS are a PITA.
Either consider aggregating your service calls to do more work so that the whole entire transaction is in one service calls or have Java handle your frontend. Otherwise see Concern 3 with Finagle.
Concern 2
I recommend you stay stateless and do REST or RCP.
It sounds like your concerned with speed which I think you shouldn't worry about till its a problem. However if you do want to do user based caching of objects I would use Redis and its pub/sub feature (or RabbitMQ + memcache).
Concern 3
Use RabbitMQ, or Redis, or/and Finagle.
MY final Opinion
I don't think you need PHP particularly if you know Java.
So much of the web app world today is moving towards Javascript (in the client) I don't see any benefit to using something like PHP serving pages when there are better options like Node.js or just sticking with Java.
And #jpkrohling is right... templating and frotend used to suck in Java but its gotten much better particularly since most of your UI code will be in Javascript anyway.
If you need an example of more modern web stuff in Java have a look at this project: MWA and also by the same author: Handlebars in Java.
To sum it up my opinion and go back to SOFEA: backend = Java and frontend = Javascript
Haven't done this before, not sure if it's a good idea, but here are some thoughts on your questions:
First of all, in the PHP world, each request (whether it uses keep-alive or not) is run as an isolated process, so this scenario is typically unheard of; it's possible to use persistent database connections, but any non-committed transactions are automatically rolled back when the request is done. Now, this is where my knowledge about Spring is lacking, because I'm not sure whether Java can keep a database connection in the same state between requests as long as the same HTTP connection is used; if so, you can use PHP + cURL to perform three HTTP requests while reusing the network connection.
Object (un)marshaling between PHP and Java will probably not work very well; a representation of the collection would have to be made in the form of perhaps a result identifier that can be fetched via REST by PHP and passed back to Java as an opaque string.
It should be noted that PHP requests are typically short-lived, which makes it a good candidate for horizontal scaling; long running processes, such as those for Pub/Sub systems, are therefore seen less often. Personally I prefer using the alternative of sending HTTP requests so that the frontend caching can be abstracted away from the Java service.
I'll add more when I think of anything else, do let me know if my answer gives you more questions :)
There is definitely no straightforward way out. You have to re-write your backend controller layer which exposes REST calls to PHP. You need to group some fine grained services and make them coarse grained.
A word of advise - you can make things work at the end day with tweaking here and there, introducing a queue or another framework or library etc - but you would have also introduced lot of Accidental complexity..
Things can get real nasty in future during maintenance, bug fixes, upgrades etc
If speed of development is a concern, explore other alternative like Play Framework 1.2.x framework, so that you can re-use your server side code as it is.

PHP RESTful Web Service for an iPhone

I'm developing an iPhone APP and need to implement also an Web Service.
First of all I'm not a Developer and never made something big in PHP, Objective-C, xCode.
My PHP knowledge isn't also good. But let's start with my Environment.
iPhone APP (xCode 4.2, iOS5), PHP Web Service, MySQL DB
I was researching the WEB and most People tend more to REST than SOAP. I think i see also the advantages of REST (using of simple HTTP Verbs (get, post, delete etc...), but that's not the main point here...
I think I understand the main goal of the REST Architecture and tried to make a little concept with an URI and Verb Mapping. Here just a simple example of the mapping:
/location/{location_id}/product
/location/{location_id}/product/{product_id}
Both are GET operations who should get me ether a single product or all products of a location.
How would a simple PHP REST Web Server look like with these functions?
Another part should implement a User Authentication from the iPhone. Somehow i need to store the user session, right now I don't have any idea how to make that. The goald is that if only a user is logged in, he could review the product.
Now I've researched also the Web but couldn't find an easy step-by-step Tutorial.
Do you know any good Tutorials which will help me achieve my goal? :)
A lot of people prefer using PHP Frameworks like ZEND. This seems very interesting, but it seems like a big package with a lot of modules.
Does someone know exactly which Modules are needed to get my Web Service working?
This is quite a good tutorial, it uses the codeigniter framework which makes the learning curve a bit steeper but makes it a lot more powerful in the long run.
http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/
If you want to build this the custom way it's actually very easy to do if you want to return information in the JSON format especially for php5 which is generally well supported amongst hosts these days.
Essentially the steps are like this:
Pass in product id via url and retrieve using GET i.e. service.php?product_id=10
Query database and return data for product id that was passed in
Store returned data in an array
Set header content-type to application/json
json_encode the result (json_encode)
That way when you call that url in a browser you will get a nice JSON formatted array result in a key:value pair manner. And as of iOS5 json parser comes with the framework (for earlier versions SBJson is a good framework to use (SB JSON))

Should I always use webservice?

HI all,
I am designing an client - server application system. The Server provide 2 features: upload and download images. The clients (maybe Iphone, Android, WP7, ...) use these features to provide to end-users.
At this time, I can design the server as web-pages (such as upload.php, download.php) as well as webservices. Both ways work fine for me.
My question is: which one I use webservices or web-pages technical for my designing? And why?
Thanks.
To be honest with you, using something like SOAP for this seems like a lot of unnecessary effort. You can very easily accomplish this using form encoded data and the right query string parameters without going through the trouble of building SOAP envelopes and writing all of the XML. Granted, the system I described is very close to a REST webservice, so I suppose it depends on what you mean by "webservice." Either way though, given relatively simple system you've outlined, I don't think something like SOAP will give you a very good return on your investment.

What are some of the pitfalls/tips one could give for developing a web service

Looking to develop a web service (api) in PHP to offer customers an easier way to integrate with our platform. There are workflow calls that will be validated with user/pass as well as some reporting options.
Sorry I can't post more details or code on the subject and I have never developed a web service but have had experience in using them via SOAP.
Now I would also need to offer a state or status of the workflow and I think REST would be the best choice here, but still looking for opinions on that.
For reporting I would like to offer different options such as XML,Excel/CSV any reason I would pick one over the other?
What are some of the pitfalls I should lookout for?
What are some gems anyone could offer.
Thanks in advance to any help as this is very important for me to understand.
UPDATE #1:
What would be the most secure method?
What is the most flexible method
(Platform independent)
UPDATE #2:
a little bit about the data flow.
Each user has creds to use the API and no data is shared between users. Usage is submit a request, the request is processed and a return is given. no updates. (Think Google) a search request is made and results are given, but in my case only one result is given.
Don't know if this is needed so it's an FYI.
Always handle errors and exceptions.
Problems will always make their presence felt in the application/api. Either at start or through further development. Don't leave this as an end task, and make it clear when an error occurs, with well documented response messages.
Also if your service will handle many requests, and for the same resource id (independent from user) the same resource is returned be sure to cache the information. And this not only for performance reasons, but for the cases when errors stuck up. This ways you can at least serve something to the client (possibly useful, more context required to be explicit).
The biggest and most important item I can offer is to guarantee your infrastructure behind the WS or at least what you are serving up via the WS is stateless. The moment you deviate form this it will become a nightmare and you will begin having to shoehorn code in to protect your data from getting fouled up.
An example would be a two clients making changes to data via the WS, ie...save configuration. How you deal with that on the back end makes things interesting. If your data is only heading outbound, you are in a much better situation then if you have to support pushing data into the back end.
Also, think out the API's in depth as with any public facing API. The moment you have a version out in the wild and then decide that API needs changed or deprecated begins to cause problems for the client base making use of your WS.
I am currently working on a web application that includes a web service (or 2 in ASP.NET MVC) and I highly recommend looking at the principles behind Service Oriented Architecture (SOA) as what I have found is that the most important aspect is to get the design of the web service API correct as that will effect the rest of your back end and either make your life easier or have you running into walls out of frustration.
Essentially SOA means design the web service around business processes, i.e. how the people who use your API are likely to use it.
A Good desgin is always a good idea, so I highly recommend you do a lot of reading on Web Sevice Design Principles before you start coding and save yourself or some other unlucky sod alot of grief latter on.
Also make sure that your design is agile as it will change frequently as communication between your company and your clients happens.
A little bit more related to implementation than design:
I would decide that the output of the service to be XML - this can be very easy parsed, by all decent languages. Also, if some client need other output, you could transform those XMLs through some XSLT processors and offer "other" web services, that outputs JSON, or whatever else they need.
Regarding the reporting, that depends on how the reports will be used - if the clients process them and they need only the data from the reports - then again suggest XML. In my opinion working with CSV is harder because you have to take in consideration all kind of special cases like "what happen if my data contains the separator field", "will the client be able to specify the separator", "how will I represent nested data", or all of these are straight forward with XML.
If your client needs reports to use them out of the box you could use BIRT -beautiful and free
Offering multiple outputs like JSON, CSV, YAML or XML is good - that gives the end user confort, at a very small cost! Dumping data is always easier than processing, and say that they already parse JSON for some reason - it is much easier to just hook that up for your API than implementing, say an XML-parser. Nowadays I see XML-parsers everywhere, so that should probably not be a problem, but I like the more "air-ish" nature of JSON; I have looked a little into YAML but never used it - but it looks promising, I'll definitively use that for the config files of my next project.
On the security side of anything that dynamically processes any input an user gives, one should treat such input like something you would not poke on even with a stick.
IMHO stateless REST is better than SOAP because it is less overhead, one can easily communicate with a REST-api by hand using curl or wget from the terminal. Jump-start so to say.
I would reccomend you to take a deep breath, a pencil & a paper, sit and sketch down everything that is going to be needed. Then you remove the less important stuff, and take a new paper and start to organize it. You can add the less important stuff in the next version of the API.
Try to design the API so that you don't lock yourself into a corner, make no assumptions on where it is going to head next.

Transform Ruby-on-Rails code to PHP

This may sound odd but a right answer might save me hours of coding. I have found a ruby-on-rails class (~10 files, ~1000 lines total) that serves a specific purpose (payment gateway integration). However, I am not familiar with ruby at all and need to use that class in a PHP application. I am wondering if there is a program that can perform the conversion for me. I understand that some portions of code might need to be hand-edited which I can manage.
No, there is no commercial, free, or open source compiler that will take any an arbitrary piece of ruby code and compile it into PHP.
The other answers are suggesting you learn enough ruby-on-rails to create a simple rest framework on top of the existing ruby code, and then use curl (or some other http/web services library) from PHP to fetch and post to URLs in your new simple rails application. These requests would trigger methods in the ruby class, which would run within ruby. There would be no direct eecution of ruby code by the php run time.
My suggestion is you'll spend less time finding payment gateway code written in PHP and using it instead.
It's quite easy to talk to a Rails app.
You could talk to it through REST calls, which is basically sending a HTTP method to an URL.
For example, a /GET to /products.xml would return you a list of all products. A /PUT to /payment/new with the appropriated params would start a new Payment model, etc.
Take in mind you'd need to know how it works, what models it has and what routes are there available on it. Luckily, Rails comes with many tools. One of them is a rake task called routes.
Execute "rake routes" and you'll be returned a list of all the URLs that Rails works with, with the needed HTTP method and supported params. With this info, you could find out how to talk to that app.
Gotcha: PUT and DELETE are both HTTP methods that currently browsers doesn't implement largely, so Rails uses a _method param. If you send a POST method with a _method:"put" param, it will proceed to act just as a /PUT method was sent.
There are no software out there to do such a thing.
You could interface with it or just take the business logic out of it and redo it from scratch if you're not familiar with Ruby on Rails.

Categories