PHP file on the server vs REST interface with abstract methods - php

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.

Related

Unit testing legacy php application — how to prevent unexpected database calls

I'm adding unit tests to a legacy PHP application that uses a MySQL compatible database. I want to write genuine unit tests that don't touch the database.
How should I avoid accidentally using a database connection?
Lots of parts of the application use static method calls to get a reference to a database connection wrapper object. If I'm looking at one of these calls I know how to use dependency injection and test doubles to avoid hitting the database from a test, but I'm not sure what to do about all the database queries that I'm not looking at at any one time, which could be some way down the call stack from the method I'm trying to test.
I've considered adding a public method to the database access class that would be called from the PHPUnit bootstrap file and set a static variable to make any further database access impossible, but I'm not keen on adding a function to the application code purely for the sake of the tests that would be harmful if called in production.
Adding tests to a legacy application can be delicate, especially unit tests. The main problem you will likely have is that most tests will be hard to write and easily become unintelligible, because they involve massive amount of setting up and mocking. At the same time you will likely not have much freedom to refactor them, so they become easier to test, because that will lead to ripple effects in the code base.
That's why I usually prefer end to end-tests. You can cover lots of ground without having to test close to the implementation and those tests are usually more useful when you want to do large scale refactoring or migrate the legacy code base later, because you ensure that the most important features you were using still work as expected.
For this approach you will need to test through the database, just not the live database. In the beginning it's probably easiest to just make a copy, but it's absolutely worthwhile to create a trimmed down database with some test fixtures from scratch. You can then use something like selenium to test your application through the web interface by describing the actions you take on the site, like go to url x, fill out a form and submit it and describe the expected outcome, like I should be on url y now and there should be a new entry in the database. As you can see these kinds of tests are written very close to what you see on the website and not so much around the implementation or the single units. This is actually intended because in a migration you might want to rip out large chunks and rewrite them. The unit tests will become completely useless then, because the implementation might change drastically, but those end2end-tests describing the functionality of the site will still remain valid.
There are multiple ways you can go about this. If you are familiar with PHPUnit you might want to try the selenium-extension. You should find tutorials for this online, for example this one: https://www.sitepoint.com/using-selenium-with-phpunit/
Another popular option for these kind of tests is Behat with the MinkExtension. In both cases the hardest part is setting up selenium, but once you are able to write a simple test, that for example goes to your frontpage and checks for some text snippet and get that running. You can write tests really fast.
One big downside of these tests is that they are very slow, because they do full web requests and in some cases have to do some waiting for JavaScript. So you should probably not test everything. Instead try to focus on the most important features. If you have some e-commerce project, maybe go through a very generic checkout procedure. Then expand on different variations that are important to you, e.g. logged in user vs. new user or adding vouchers to the basket. Another good way to start is write very stupid tests, that just check whether your urls are actually accessible, so go to url and check for status code and some expected text snippet. Those are not really that useful in terms of making sure your application behaves correctly, but they still give you some safety as to whether some random 500 errors appear out of the blue.
This is probably the best approach for making safe your app works well and make it easier to upgrade, refactor or migrate your application or parts of it. Additionally whenever you add new features, try to write some actual unit tests for them. It's probably easiest if they are not too connected with the old parts of the code. In the best case scenario you won't have to worry too much about the database, because you can replace the data you get from the database with some instances you prepare yourself in the test and then just test whatever feature. Obviously if it's something like a simple we want to have a form that adds this data to the database, you will probably still not want to write a unit test, but instead write one of those bigger end to end-tests instead.

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.

What is the Best Workflow for Web Application?

I am about to begin a web application. Before I begin, I would like to get some advice as to what the best work flow/order is for creating a web application such as this.
My project will consist of a server-side with PHP and MySQL. The client-side will be XHtml, CSS and jQuery. There will also be AJAX used.
I'm sure that it can depend on certain situations, but, overall, what is the best order for developing a project with these credentials?
Should I start developing the server-side first? Or should I begin with the client-side? Or should I do both at the same time? What about the database - should that be a first priority? Then perhaps the DAOs?
Start with the data first. The server-side data is the persistent, essential core of the application. If this data model isn't right, you have nothing.
You should be able to unit test the data model to prove that you have the right attributes and relationships. This doesn't require much. A few test cases to insert, update and query.
You will support that data model with back-end processing.
This, too, should be unit tested to demonstrate that it works and does all the right things to your data model. This will be a bit more complex, since this processing is the application.
Then you can think about the data model as exposed by web services to Ajax.
This, also, is testable to prove that the JSON does the right things. This testing is often fairly complex because this is what the GUI front-end relies on. This has to be right.
Then, once you have that Ajax data model worked out, you can write the front-end GUI.
The workflow you're describing is what I use for my own (solo) projects.
I like to meet in the middle. I do data modeling first, and simultaneously start prototyping the interface. Business rules come last and pull everything together.
I also find it "inspiring" when I have a GUI to look at... it encourages me to make it do something. Furthermore, GUI's tend to undergo the most revising, so starting them early in the process ensures you'll be happy with the finished product, and that it'll be finalized by the time your business logic is implemented.
If I'm working for a big company that's not sure of exactly what they want, I'll start with the UI first. This way they get to figure out what they want before I've put a lot of time into the rest of the system.
On the other hand, if I know exactly what is needed, then I will start with one feature and work my way up through the layers, database, controller, view, and ajax, until that feature is done, and then go on to the next feature. This way I've got less context to remember, and the client always has something new to play with.
I can't tell you what's absolutely best, but what works for me is...
Talk to the business people to get an idea of what they want.
Draw the UI with pen and paper. Boxes represent pages. Buttons and links have arrows pointing to other pages. Don't need every microscopic detail. Some things are implicit.
Once the UI is mapped out pretty well, design the DB schema. Sometimes I'll write out all the tables in a text file like this...
pets
----
id
name
species
# etc...
Then implement the database. I use Rails migrations. You might write the DDL manually.
If you have models or DAOs or something along those lines I would implement those next, with unit tests.
Then I usually work through the app entity by entity. Get the view and controllers working. Rapidly switching between the testing code and the implementation code.
That's the general sequence, but the whole time there are adjustments and so on. You'll need to go back to your DB design and evolve that as you build the actual functionality.

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