Accessing a PHP method - php

I'm about to start working on a project for an organization using C#. In order to get the necessary data I have to get the data from a database, however, I will not be given access to the database even to create the application. As you can assume this creates a bit of a challenge.
In a past project I created a PHP script that accessed a database for me and returned the data in JSON format. I'd like to the same, unfortunately there are around 100-120 queries that I would need to be able to make so it would be very time consuming to create a PHP script for every query that I need.
Is it possible to create a method in PHP that takes in a string argument and then use somehow pass the string into it from C#? If so then how can I do it? If I can pass a string to the method within the script then it would only take 3 methods (in the PHP script) in order to make all the necessary queries.

A naive example of invoking a PHP method from a C# application/library would involve using the WebRequest and WebResponse classes:
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("http://server/script.php?method=my_method");
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Stream stream = response.GetResponseStream();
Using the stream, you can then parse through or deserialize the response, if it's a JSON string for example.
This implementation relies on script.php using the method parameter, and delegating the call to that method; pseudo-routing if you will. More arguments can be passed via the query-string, and used by the invoked method.
Another trivial example of this:
$r = new Repository();
$d = $r->{$_GET['method']}();
echo json_encode($d);
However, much of this can be implemented using existing technologies. Exposing the PHP methods as an API is something which has been done over to death, and a plethora of RESTful API frameworks exist to expedite the development of such applications. The same goes for C# applications/libraries consuming an API, provided you use something with a client implementation.
The answer to your question, "Is it possible..."; certainly yes, however this is a pretty high level requirement, and the implementation will rely completely on the problem domain.
As an elaboration (might have been too long for a comment) I'm currently working on a massive overhaul project. The previous developers decided to roll their own everything. What did that mean for me? I couldn't reuse an ounce of their code-base. They had rolled their own security strategies. Garbage.
I don't say garbage because I could write better (I might, but not much), but because I know better.
I favored well established technologies, ones that integrate well and have massive community and developer support. When I have a problem, between the docs and here, I can normally find a solution pretty quickly. Furthermore, issues with the components are documented, fixed, and can be worked around.
Rolling your own integral components (be them security or otherwise) for production, especially when you know you're treating it like a learning experience, is irresponsible.

Related

PHP file on the server vs REST interface with abstract methods

I can create a PHP file on my sever that will handle GET POST PUT DELETE requests, and I can can return the correct data for each case to the requestor from the same file.
example:
user.php (if someone sends a REQUEST to user/ or user/1 they will get back a seemingly RESTful response of all users or the one they requested).
I am having a tough time understanding why I need to build a REST interface instead of just writing the correlating PHP files for each endpoint I want to expose?
So after building my REST server using 3 different methods, I now fully understand the need to abstract out the interface. It is far simpler to maintain one point of entry then 10 or 20 different PHP files.
don't get me wrong, at first, when implementing the abstract interface, you will write a lot more code, but it quickly saves you hours of time in the long run. It also allows you to stay flexible and interchangeable.
my summary:
if you just need quick and dirty go php file!!
But, if you plan on building something secure and scalable, bite the bullet and build the interface.

Strategies for implementing a REST like API in an existing web-application

Currently we have a lot of web pages that either have SQL statements embedded in them or call a specific php script that does a specific job - ie getNames.php - as part of a ajax call back. Neither are particularly maintainable.
I was thinking about using a REST like API to get the necessary data to the client and then munge the data into something usable. This is attractive as this lessens the burden on maintaining highly complex sql in code and allows centralisation of data (so just one AJAX call to get the data not lots of little ones). Also allows the database to change lessening the impact on the client.
However there are two problems I can see with this strategy:
The site is a game, and so I need the RESTlike API to be protected from abuse/cheating as much as possible.
All examples of REST API's use a controller to handle the requests in root. That's not ideal for me since we are at //company/games/game/ and there already is an index.php at root (//company/).
What options and strategies do I have for the two constraints I listed?
Well, you're asking for opinion, but I'm well seasoned enough (having written many many API schemes over the years) that I'm totally willing to open myself up to Net abuse. I think the key here, and this should provide an opinion to work from on both of your questions, is that REST is simply a set of principles. Sure there are people that follow a RESTful pattern explicitly, but that isn't practical for most people.
Take the Flickr "REST" API for instance... a call may look like this: http://api.flickr.com/services/rest/?method=flickr.favorites.getContext&api_key=a114adf91150953107987e4c3dc14df8&photo_id=6033564557&format=json&nojsoncallback=1&api_sig=0d2c215992d643ef6fe4a085805f7059
Not very RESTful, from a patterning perspective... however, it contains all of the elements of REST and is a fine enough model. You can understand what it is doing at a glance, and you can easily build on top of that.
IN the end, REST is a set of principals, not a protocol, and not even a pattern in and of itself. You're free to implement it however you want. There's always an interoperability intermediate layer and the point is to just make it understandable... and many of the REST patterns actually get in the way of that, favoring form over function.
In fact, most of the patterns I've seen are insufficient for anything particularly advanced, but that's part of the point of REST... Keep It Simple (Stupid).

Theory/Magic behind creating API

Im a newbie PHP programmer and I have a few questions about creating a REST based API service.
Basically, its going to be a github open source project which is going to scrape various data off the web and offer it as an API in XML. Now here are my questions in terms of how should I or how can I do this.
1) Since there isnt a robust/same pattern for getting various data through scraping, what is the best way to actually output the xml?
I mean the PHP file would have various lines of extracting data from various points in the code and the file would be a lot of lines. Is it a good idea to type the code to output the result in there?
2) Is there a way to organize the scraping code in a sort of class?
I cant think of a way that would work besides linear approach where not even a function is created and you just apply functions (in general).
3) If theres a way to do that ^^ , how can it you output it?
Is there any other approach besides using another file and getting the contents from the main file and displaying the code through the secondary file.
4) If I were to offer the API in XML and JSON, is there a way to port from one result to another or will I have to manually create the fields in json or xml and place the content in there?
I might have more questions that might arise after these have been answered but I hope I get everything cleared up. Also, this is assuming that the results are not fetched from a DB so the data has to be scraped/tabulated on every request. (even though caching will be implemented later)
Thanks
This question is probably more appropriate on https://codereview.stackexchange.com/
Not to be rude, but a newbie programmer developing an API is like a first-year med student offering to do open-heart transplants for free. I understand that you believe that you can program, but if you intend to release publicly accessible code, you probably need more experience. Otherwise guys like me will muck through it and file bug reports ridiculing your code.
That said, if you want theory of good API design you should probably check out Head First Object Oriented Analysis and Design. You'll want to focus on these key concepts
Program to an Interface, not an Implementation
Encapsulate what varies
...and follow other good design principles.
...honestly, there's a lot to cover to good interface and good systems design. You can use this as a learning exercise, but let people know they shouldn't rely on your code. Though they should know that screen scraping is far more brittle and instable than web service API requests anyway, but many don't.
That said, to provide some initial guidance:
Yes, use OOP. Encapsulate the part that actually does the scraping (presumably using cURL) in a class. This will allow you to switch scraping engines transparently to the end user. Encapsulate your outputs in classes, which will allow for easy extension (i.e. if JSON output is in a Single Responsibility class and XML Output is in another, I can add RSS Output easily by making a new class without breaking your old code)
Think about the contracts your code must live up to. That will drive the interface. If you are scraping a particular type of data (say, sports scores for a given day), those should drive the types of operations available (i.e. function getSportsScoresForDate(date toGet))
Start with your most abstract/general operations at a top level interface, then use other interfaces that extend that interface. This allows users to have interfaces at different levels of granularity (i.e. class SensorDataInterface has a method getData(). HeartRateMonitorInterface extends SensorDataInterface and adds getDataForTimeInterval())

Easiest RPC client method in 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.

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