Dynamic Enumeration in PHP. Possible? Sensible? - php

I am building an API which will accept a variety of metrics from an iPhone application.
The App Programmer has requested that the API be able to handle types of metrics the API does not yet know about. I would like to use an enumeration to list the current types of Metrics, but new metrics would have to be added as they are pushed to the server.
Has anyone seen this done before? I've thought about using a DB instead of an enum, but that seems really messy.
Any thoughts?

Don't use an enumeration. Enumerations are primarily useful for when the entire range of values is known ahead of time; this is clearly not your case.

Related

is there a package for making a simple query API?

I have simple, 1 table, data source that I want to be able to query through an API.
I want to be able to query on any one of the columns. Ideally, I could query for multiple values per column. One column has text, for which I need to be able to do partial and approximate matches (as well as handle diacriticals)
I am wondering what packages people recommend for building this. I realize its something simple, but it seems like a common enough goal that I thought there would be something available to do all the heavy lifting.
Ideally, I'd like to work with python/django, but could also do PHP. Is there something available to help with this?
I assume since you mentioned django, that you are asking to create a web facing API (like what twitter and facebook provide), if that's the case there are a few options:
You may not have to write anything at all. There are platforms like apigee that allow you to create an API just by clicking a few links. They have free accounts, like almost everyone on the net.
If that doesn't work for you, you can use flask-rest (optimized for the Flask microframework) or tastypie which works great with django for Python. Both will allow you to easily create APIs for your data source and they will take care of most of the boilerplate code for you.
For PHP, someone already asked the same question earlier so that would be a good resource.
If you just want to create an API on top of an existing database and use this API to query the database in other applications, then the de-facto standard for Python is SQLAlchemy.
Probably you may want to check out this link, that will give you some lights about structuring and some template code (in PHP) for building an API:
http://net.tutsplus.com/tutorials/php/creating-an-api-centric-web-application/
From the formatting of the URL to the call of the methods called in it. I.e.:
$controller = ucfirst(strtolower($params['controller']));
import sqlite3
conn = sqlite3.connect("some_db.sqlite")
conn.execute("SELECT * FROM TABLE WHERE some_field=?",('field_value',)) #this should properly escape values
# or
conn.execute("SELECT * FROM TABLE WHERE some_field LIKE ?",('%parial_match%',))
not sure if thats what you are asking for (this is python)

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))

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())

Is there a 'best' Google charts API for PHP?

Is there a "best" one? Does it offer as much flexibility as the Google API?
I am wary of using such wrapper, as I would need to take the time to evaluate each individually, so I am asking here if anyone has already done this.
Are there any benefits in a wrapper? The Google API seems clear enough.
And what guarantee is there that a wrapper will be updated as Google updates its API.
I would need something that can be used commercially. Should I even bother to look, or just stick with Goggle's API?
I woudl prefer to use POST, for larger datasets (and privacy).
Btw, please don't just google & post some links - I can do that myself. I'd like to hear from people who have actually used a wrapper. Thanks.
This makes an interesting read; it's the sort of thing I want to hear more of.
"What I was especially missing was some logic that automagically prepares the data for the chart. Eg. I'd expect the library to create sensible scaled axis labels on its own."
There is a good list of wrappers here
There is never a "best". Only a better for your case.
Various chart API exist, see http://free-wiz.blogspot.com/2008/07/best-free-chart-apis.html
gchartphp look nice and recently updated, http://code.google.com/p/gchartphp/

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.

Categories