I left last week's post by telling you about the creation of functions api_backbone
and create_SQL_clause
. This week, I started with re-factoring those functions.
The first issue with api_backbone
was that there were too many arguments to be passed. The readability was taking a hit and by simply looking at a function call, it was difficult to understand which parameters represented what.
The simple solution to this was passing arguments like we do in JavaScript. Therefore, the code ended up looking something like the following.
function api_backbone($options) {
/*
* Function to perform all API calls
* Every call has a token, checks access level and performs a query
* This function takes those as argument and logs the request
*/
$defaults = array(
"request_type" => HTTP_GET,
"access_level" => ADMIN_ACCESS_LEVEL,
"member_id" => -1
);
$options = array_merge($defaults, $options);
...
}
array_merge
does exactly what $.extend()
did, replacing common keys with values of options
, but keeping the defaults
in case they weren't present in options
.
Some notable options in the function api_backbone
are as follows.
returned_id_name
- Set it totrue
andmysql_insert_id
is run after anINSERT
call. Useful inPOST
calls to create objects.query_id_existence
andquery_id_existence_array
contain the query to be run to check if an object exists, before the main query (typically to edit or delete it) is run.one_row
istrue
when the result of the query is supposed to consist of a single row.
The next task I did was to introduce a debug mode in the API. I figured it was difficult to print the query using vsprintf
every time there was an error in the SQL query. That is why, I set a constant DEBUG
in api/core/constants.php
to true
. Now, for every call to api_backbone
, irrespective of the situation, prints the query being executed.
Another small, but significant change in terms of efficiency was the addition of JOIN
to my SQL queries. I was using just the alias syntax, but a discussion on the SitePoint forums tells me that JOIN
is more efficient. Since I am not an expert on the topic, I just took the advice.
The next change was to add a boilerplate class, which one could just copy the directory and start off a new app (after reading the inline comments of course).
Lastly, I tried create a few API calls using the functions that I had made. Turns out the task is pretty easy now. PUT
, POST
for courses and a few GET
calls for member lists is what I accomplished in almost no time!
Another great week (this time, I didn't miss a post... yet) and here's hoping the next week is even better!
P.S. Mid Term evaluations are just a few days away. I double checked my proposal to ensure that I am well ahead of the schedule.