FROM January 1 2012, readers who submit comments to Cairns.com.au must provide their full name and a suburb or town before comments are considered for publication.
Archive for December, 2011
PEOPLE dreaming of riches are expected to rush Far Northern newsagents testing their luck for tonight’s $31 million Gold Lotto megadraw.
Friday night shopping could finally be a possibility for all Queenslanders in 2012.
TWELVE months after the disappearance of 56-year-old Kenneth Rodman from a beach at Mowbray, his family and police are still no closer to understanding what may have happened <br>to him.
WHITE ROCK residents have been urged to take care around known wallaby habitats after an attack on a six-year-old boy.
FAR Northern children are among the most at risk in the state of becoming victims of sexual assault, but a leading child protection advocate says the State Government is keeping their parents in the dark.
TOURISTS might be thin on the ground in the Daintree at the moment but a variety of baby animals at the Daintree Wild Zoo are more than making up for it in the entertainment stakes.
Good gosh; another year comes to a close. Sometimes, it feels as if every year passes by more quickly than the one before it. Nonetheless, 2011 was a great year for Nettuts+. Here’s why…
Traffic
Honestly, these days, I don’t focus on traffic too much. That might come as a surprise, considering that this is a blog that, yes, brings in income. However, I’ve come to learn that obsessing over traffic only translates to you spending less time creating content. I’ve never taken a stance, such as, “Next month’s traffic needs to be up by 15%.” It doesn’t work that way.
Personally, I only use Google Analytics to:
- Determine what sorts of content you readers don’t enjoy as much.
- Get a birds eye view of how the site is performing. For example, 2011′s numbers, as a whole, are up 23% over 2010′s. That may not sound like much, but for us, that amounts to millions and millions of new visitors.
- Pinpoint which search queries are most popular. That way, I can be sure to commission appropriate tutorials.
Beyond that, I honestly don’t see much point in obsessively focusing on traffic.
Dedicate your life to a given topic, write about it as well as you are capable of, and I promise that the traffic will come as a result.
In 2012…
To project numbers for 2012 would almost be a contradiction of what I just wrote. That said, I suppose it would be nice for us to continue reaching more and more people!
Editorials
Nettuts+ was initially created with one simple goal: provide high quality, step-by-step web development tutorials. This year, I decided that we need to have more of a voice in the community. Initially, this took the form of me venting to an online journal… read by millions of people. Since then, though, the Editorials category has morphed into developers providing their own strong opinions on one issue or another. The reader is then left with the article (and the comments) to determine what his or her own views on the subject are. The most important thing is that it gets us talking.
- Should You Learn CoffeeScript? Developers Sound Off.
- Are jQuery Users Fools?
- Is Conference Pricing Out of Control?
- Why Many Developers Hate ASP.NET…and Why They’re Wrong
- An Introvert Reflects On His First Presentation
In 2012…
I hope to provide even more opinion-based editorials on Nettuts+. My goal is that, when a well-known developer needs to get something off his chest – whether it be the state of the industry, the people, or the tools available – he comes to Nettuts+ to write and publish it.
I want Nettuts+ to be the central location for the web development industry to come together and discuss important issues and events.
Apps
One of my goals for 2011 was to have Nettuts+ branch out a bit. Yes, we have the blog, but what about books, tools, and apps? We’re still very much in the early stages of these goals, though, we’ve made some good progress.
Nettuts+ Prefixr
Prefixr was built out of necessity, and provides us with a way to automate the creation of all those tedious CSS vendor prefixes. Now, from your favorite code editor, you only need to type a shortcut key, and your entire stylesheet will be run through the Prefixr web service, and automatically optimized. No longer do you need to worry about which browsers support which CSS3 properties. Prefixr does that for you.
Nettuts+ Builder
Unfortunately, it costs money to commission these apps; so we’ve experimented with selling them as cheaply as possible on the popular CodeCanyon marketplace.

Nettuts+ Builder turns the process of compressing scripts and stylesheets, and uploading a project to your server into as simple a process as possible.
Let’s say that you finished a coding project or demo. Simply drag the folder onto the Builder menu icon, and it will:
- Create a new “Publish” directory
- Compress all JavaScript files
- Compress all Stylesheets
- Concatenate all assets
- Optionally upload them, via FTP , to a designated folder on your server.
If you’ve found yourself manually compressing your files and uploading them to your server, this automates the entire process!
Structurer Pro

Structurer is a wonderful project tempting interface for the Mac. It allows you to rapidly create directory structures with ease, and a few of the features include:
- Always find yourself manually creating the same files and directories? Not anymore.
- Need to download the latest version of the CodeIgniter framework? Or how about WordPress? With Structurer, it can be done in two seconds!
- Need to assign custom text to new files – for example, adding a base plugin snippet to a JavaScript file? That’s a cinch in Structurer!
In 2012…
Branching out to provide apps and web services is a fantastic way to both spread your brand, and provide helpful services to your peers. In 2012, I’ll be focusing on commissioning more cross-OS apps, and creating additional web applications and services. For example, I don’t think that the online code snippet management and community idea has been executed well enough by anyone. Sites like Snipplr are helpful, but fall far short of what they could be.
Additionally, we’ll also focus on smaller tools, such as plugins, code editor extensions, and more.
The Best Way to Learn…
Newcomers are begging for these sorts of resources.
Something I’ve thought about quite a bit – particularly in the last several months – is syllabus based education. For instance, if you want to learn JavaScript, you have literally thousands of resources available to you. As amazing as that is, it’s almost a hindrance; where do you start? Very quickly, you can become overwhelmed. Wouldn’t it be helpful if you were given a syllabus by a pro? Want to learn JavaScript? Great – read this, then this, then this, follow and become friends with these people on Twitter, try out this first project, etc. Newcomers are begging for these sorts of resources.
As a first step, we’ve created a series tailor-made for this group of people: The Best Way to Learn.
In 2012…
We’re only four entries in so far; in 2012, I’d like to increase this number to cover all sorts of languages and tools.
Two Man Ship
While Nettuts+ is a part of the Envato network, when it comes to the day-to-day management, it had always been little-ole me at the helm. Thankfully, this year, Siddharth has come on board as my assistant, and has been doing an excellent job. In addition to helping me edit and publish articles (so that I can focus more on Premium courses and books), he’s also the man behind our fun Nettuts+ Quizzes that you guys seem to enjoy. He’s been a huge asset to the site.
In 2012…
I hope to transition Sid into more of a co-pilot, rather than assistant. It’ll be nice to reach a point when we are both responsible for finding, commissioning, and scheduling top quality content.
Nettuts+ Live
Take the Nettuts+ format (step by step tutorial), and translate it to a live, real-time coding tutorial on stage.
A few months ago, when speaking at a WordPress meetup in New York, I experimented with a format that I call “Nettuts+ Live.” The basic idea is that you take the Nettuts+ format (step by step tutorials), and translate it to a live, real-time coding tutorial on stage.
For my presentation, I discussed WordPress custom post types and taxonomies, and how they can be used to extend your WordPress application. Now, in hindsight, I’m not sure I would do it the same way again. Coding from scratch in front of a hundred people is very, very difficult. With that in mind, I think I did quite well, though there were a few points when I had to stop and stare at the code blankly for a couple moments…desperately trying to determine what typo I had made.
And then, when I finished the presentation, I was met with the realization that only a handful of the people in the audience were actual coders; the rest were mostly WordPress users. Yikes!
In 2012…
Nonetheless, I think the format has merit, if molded a bit more. In 2012, I’m going to experiment with more local meetups and this format. No slides; just a code editor, a speaker, and lots of questions from the audience along the way. It may crash and burn, but it also may…not!
Courses
As part of the newly relaunched Premium brand of Tuts+, Tuts+ Premium, I’m the head of web development courses. Mostly, what this translates to is me creating the best possible content for learning how to be a web developer – in video form.
Particularly in the last few months, I’ve immersed myself in the art of screencasting and teaching. I’ve watched countless video tutorials around the web to determine what I enjoyed, what it irritated me, and what makes me press stop. At a glance…
- Umms: I can’t help it; when a teacher speaks too many umms and ahhs, it drives me crazy. “Next we’re uhhhhhhh going to create this
div. - Massive Snippets: If you’re creating a screencast, your goal is to teach right? In that case, don’t paste twenty lines of code into the editor at a time. Many of the viewers will be working along; don’t flood them with unexplained code snippets. Write that stuff by hand, but…
- Wasting Time: Don’t make the viewer wait for you. A pet peeve of mine is watching a screencaster take 60 seconds to write a single line. You can edit these pauses out when you’re finished recording. For instance, rather than, over the course of twenty seconds, writing
document.getElementById('myElem');, simply say, “Next, we’re going to retrieve the element with anidofmyElem. Then, either immediately cut to the finished line, or speed up the video while you write it. It’s painful otherwise. - Teach, Fool: I’m amazed by how many people don’t make the connection that they should be teaching. A screencast is not a place to illustrate how smart and clever you are. Explain exactly what each line is doing; never assume that all viewers are on the same skill-level. In my videos, I often say, “I’m going to explain this section in more detail, but, if you already understand it, fast-forward a couple minutes in the video.”
- Audio Quality: My first videos were awful, and used the built-in microphone. Thankfully, I’ve come a long ways since then. If you enjoy creating video tutorials, please invest in a good microphone; it makes an enormous difference. In the last few months, I’ve switched to the Rode NTG. Highly recommended!
- Zooming: This is the worst of the bunch; especially for coding tutorials, don’t record at 600×400, and make the viewer dizzy every time your mouse moves from one side of your screen to the other, while the video recorder transitions left to right quickly. Instead, reduce the resolution of your monitor to around 1280×720, and record full screen.
In 2012…
At the moment, I’m still working to get the bread and butter courses up on the site, such as CSS3, JavaScript, jQuery, PHP, etc. Once the staples are finished, we’ll transition into more specific courses, such as Backbone Essentials, CodeIgniter, Dojo, etc. It’s a really exciting time to be a Tut+ Premium member.
Changing the Landscape of Online Education
Brick and mortar colleges are dated, and incredibly expensive.
Nettuts+ began in 2008, when Envato was still referred to as Eden. Since then, the site has come a really long way. My favorite part has been the process of determining and defining exactly what sort of site it is. I love that we offer video tutorials, and sessions, and in depth articles from some of the most respected developers in our industry. Every time one of my dev heroes links to a Nettuts+ article, it makes me feel amazing. This site will continue to grow; so “stay the course” is the name of the game for Nettuts+ and 2012.
In 2012…
Tuts+ Premium has taken the first step. The next one will be a significantly larger leap forward.
For me, I want to redefine the landscape of online web development education entirely. I want to take the basic college experience, and translate it to the web. No, I’m not talking about keg parties, I’m talking about a community for students.
I’ve heard it too many times: “My college hasn’t taught me a fraction of what Nettuts+ has in two weeks.” I’m not being conceited here; replace Nettuts+ with any popular web development blog, and the outcome will still be true. Because our industry is accelerating at such an incredible speed, traditional schools and professors can not keep up. Brick and mortar colleges are dated, and incredibly expensive.
I want Tuts+ Premium to bridge the gap: provide students with instructors, courses, quizzes, assignments, one-on-one lessons, certifications, and forums to learn and collaborate with their peers. In its current form, Tuts+ Premium has taken the first step. The next one will be a significantly larger leap forward.
Help Me
This final question is for you, John Q Reader. How can I make Nettuts+ the best web development resource on the web? In the last three years, we’ve come a very long way toward this goal. How can I take it further? What do you need more of from us? In return, I promise we’ll do our best to provide it. We’re currently working on the next design for the Tuts+ sites; your input will help define the shape it takes!
Planning to start working on a new web application? In this tutorial, we’ll discuss how to create an API-centric web application, and explain why this is essential in today’s multi-platform world.
Introduction
API?
For those who are unfamiliar with the term, API is short for Application Programming Interface. According to Wikipedia:
An application programming interface (API) is a source code based specification intended to be used as an interface by software components to communicate with each other. An API may include specifications for routines, data structures, object classes, and variables.
In simpler terms, an API refers to a set of functions built into an application, which can be used by other applications (or by itself, as we’ll see later), to interact with the application. An API is a great way to expose an application’s functionality to external applications safely and securely, since all functionality that these external applications can do is limited with what functionality is exposed in the API.
What’s an “API-Centric” Web Application?
An API-Centric Web Application is a web application that basically executes most, if not, all its functionality through API calls.
An API-Centric Web Application is a web application that basically executes most, if not, all its functionality through API calls. For example, if you were to log in a user, you would send his credentials to the API, and the API would return to you a result saying if the user provided the correct user-password combination.
Another characteristic of an API-Centric Web Application is that the API will always be stateless, meaning it can’t recognize API calls by session. Since API calls will be made by usually via the backend code, it will be hard to implement session handling, since there are usually no cookies involved in that. This limitation is actually good — this “forces” a developer to build an API that works not based on the state of the current user, but rather on functionality, which in turn, makes it easier to test, since the current state of a user doesn’t need to be recreated.
Why go through all this trouble?
As web developers, we’ve seen technology evolve first hand. It’s common knowledge that people today don’t just use applications via a browser, but through other gadgets, like mobile phones and tablets. For example, this article on Mashable, entitled “Consumers Now Spending More Time on Mobile Apps Than the Web”, states:
Consumers are spending more time on mobile apps than on the web for the first time, a new report claims.
Flurry compared its mobile data to stats from comScore and Alexa, and found that in June, consumers spent 81 minutes per day using mobile apps, compared to 74 minutes of web surfing.
Here’s a more recent article from ReadWriteWeb, entitled “More People Browse On Mobile Than Use IE6 & IE7 Combined:
The latest data on browser trends from Sitepoint show that more people browse the Web on smartphones than use Internet Explorer 6 and 7 combined. Those two old clunkers have been the bugbears of Web developers for years, requiring sites to degrade as nicely as possible to that least common denominator of browsers. But it’s a new world now; 6.95% of Web activity in November 2011 was on mobile browsers, and only 6.49% was on IE 6 or 7.
As we can clearly see, more and more people get their news from alternative venues, specifically mobile devices.
What does this have to do with me creating an API-Centric Web Application?
This would inevitably lead to more usage of our application, since it can be used anywhere a person wants.
One of the main advantages of creating an API-centric application is that it helps you build functionality that can be used by ANY device, be it a browser, a mobile phone, a tablet, or even a desktop app. All you need to do is to create the API in such a way that all these devices can communicate with it, and voila! You’ll have built a centralized application that can take input and execute functionality from any device that a person has!
API-Centric Application Diagram
By creating an application in this manner, we’re able to easily take advantage of the different mediums used by different people. This would inevitably lead to more usage of an application, since it can be used anywhere a person wants.
To drive the point home, here’s an article about Twitter’s new redesigned website, which tells us about how they now use their API to power Twitter.com, essentially making it API-centric:
One of the most important architectural changes is that Twitter.com is now a client of our own API. It fetches data from the same endpoints that the mobile site, our apps for iPhone, iPad, Android, and every third-party application use. This shift allowed us to allocate more resources to the API team, generating over 40 patches. In the initial page load and every call from the client, all data is now fetched from a highly optimized JSON fragment cache.
In this tutorial, we’ll be creating a simple TODO list application that is API-Centric and create one front-end client on the browser that interacts with our TODO list application. By the end, you’ll know the integral parts of an API-Centric application, and at the same time, how to facilitate secure communication between the two. With that in mind, let’s begin!
Step 1: Plan the Application’s Functions
The TODO application we’ll be building in this tutorial will have the basic CRUD functions:
- Create TODO Items
- Read TODO Items
- Update TODO Items (rename, mark as done, mark as undone)
- Delete TODO Items
Each TODO item will have:
- a Title
- a Date Due
- a Description
- a flag to tell if the TODO Item Is Done
Let’s mockup the application as well so we have a guide on how it should look like afterwards:
SimpleTODO Mockup
Step 2: Create the API Server
Since we’re developing an API-Centric application, we’ll be creating two “projects”: the API Server, and the Front-end Client. Let’s begin by creating the API server first.
On your web server’s folder, create a folder named simpletodo_api, and create an index.php file. This index.php file will act as a front controller for the API, so all requests to the API server will be made through this file. Open it up and put the following code inside:
<?php
// Define path to data folder
define('DATA_PATH', realpath(dirname(__FILE__).'/data'));
//include our models
include_once 'models/TodoItem.php';
//wrap the whole thing in a try-catch block to catch any wayward exceptions!
try {
//get all of the parameters in the POST/GET request
$params = $_REQUEST;
//get the controller and format it correctly so the first
//letter is always capitalized
$controller = ucfirst(strtolower($params['controller']));
//get the action and format it correctly so all the
//letters are not capitalized, and append 'Action'
$action = strtolower($params['action']).'Action';
//check if the controller exists. if not, throw an exception
if( file_exists("controllers/{$controller}.php") ) {
include_once "controllers/{$controller}.php";
} else {
throw new Exception('Controller is invalid.');
}
//create a new instance of the controller, and pass
//it the parameters from the request
$controller = new $controller($params);
//check if the action exists in the controller. if not, throw an exception.
if( method_exists($controller, $action) === false ) {
throw new Exception('Action is invalid.');
}
//execute the action
$result['data'] = $controller->$action();
$result['success'] = true;
} catch( Exception $e ) {
//catch any exceptions and report the problem
$result = array();
$result['success'] = false;
$result['errormsg'] = $e->getMessage();
}
//echo the result of the API call
echo json_encode($result);
exit();
What we’ve essentially built here is a simple front controller that does the following:
- Accept an API call with any number of parameters
- Extract the
ControllerandActionfor the API call - Make the necessary checks to ensure that the
ControllerandActionexist - Execute the API call
- Catch errors, if any
- Send back a result to the caller
Besides the index.php file, create three folders: a controllers, models and data folder.
- The controllers folder will contain all the controllers we’ll be using for the API server. We’ll be building it using the MVC architecture to make the structure of the API server cleaner and more organized.
- The models folder will contain all the data models for the API server.
- The data folder will be where the API server saves any data
Go into the controllers folder and create a file called Todo.php. This will be our controller for any TODO list related tasks. With the functions we’ll be needing for our TODO application in mind, create the necessary methods for the Todo controller:
<?php
class Todo
{
private $_params;
public function __construct($params)
{
$this->_params = $params;
}
public function createAction()
{
//create a new todo item
}
public function readAction()
{
//read all the todo items
}
public function updateAction()
{
//update a todo item
}
public function deleteAction()
{
//delete a todo item
}
}
Now, add the necessary functionality to each action. I’ll provide the code for the createAction method and I’ll leave it up to you to create the code for the other methods. If you’re not in the mood though, you can just download the source code for the demo and copy it from there.
public function createAction()
{
//create a new todo item
$todo = new TodoItem();
$todo->title = $this->_params['title'];
$todo->description = $this->_params['description'];
$todo->due_date = $this->_params['due_date'];
$todo->is_done = 'false';
//pass the user's username and password to authenticate the user
$todo->save($this->_params['username'], $this->_params['userpass']);
//return the todo item in array format
return $todo->toArray();
}
Create TodoItem.php inside the models folder so we can create the “item creation” code. Take note that I won’t be connecting to a database, rather, I’ll be saving the information into files. It should be relatively easy though to make this work with any database.
<?php
class TodoItem
{
public $todo_id;
public $title;
public $description;
public $due_date;
public $is_done;
public function save($username, $userpass)
{
//get the username/password hash
$userhash = sha1("{$username}_{$userpass}");
if( is_dir(DATA_PATH."/{$userhash}") === false ) {
mkdir(DATA_PATH."/{$userhash}");
}
//if the $todo_id isn't set yet, it means we need to create a new todo item
if( is_null($this->todo_id) || !is_numeric($this->todo_id) ) {
//the todo id is the current time
$this->todo_id = time();
}
//get the array version of this todo item
$todo_item_array = $this->toArray();
//save the serialized array version into a file
$success = file_put_contents(DATA_PATH."/{$userhash}/{$this->todo_id}.txt", serialize($todo_item_array));
//if saving was not successful, throw an exception
if( $success === false ) {
throw new Exception('Failed to save todo item');
}
//return the array version
return $todo_item_array;
}
public function toArray()
{
//return an array version of the todo item
return array(
'todo_id' => $this->todo_id,
'title' => $this->title,
'description' => $this->description,
'due_date' => $this->due_date,
'is_done' => $this->is_done
);
}
}
The createAction method calls two functions on the TodoItem model:
- save() – this saves the
TodoIteminto a file, as well as set thetodo_idfor theTodoItemif necessary - toArray() – this returns an array version of the
TodoItem, where the variables are the array’s indexes
Since the API is called via HTTP requests, let’s test that API call by calling it through the browser:
If everything worked, you should see a new folder inside the data folder, and inside that folder, you should see a file with the following content:
createAction() result
Congratulations! You’ve successfully created an API server and made an API call!
Step 3: Secure the API Server with an APP ID and APP SECRET
Currently, the API server is set to accept ALL API requests. We’ll need to limit it to our own applications only, to ensure that only our own front-end clients are able to make API requests. Alternatively, you can actually create a system wherein users can create their own applications that have access to your API server, similar to how Facebook and Twitter applications work.
Begin by creating a set of id-key pairs for the clients that will be using the API server. Since this is just a demo, we can use any random, 32 character string. For the APP ID, let’s say it’s application APP001.
Open the index.php file again, and then update it with the following code:
<?php
// Define path to data folder
define('DATA_PATH', realpath(dirname(__FILE__).'/data'));
//Define our id-key pairs
$applications = array(
'APP001' => '28e336ac6c9423d946ba02d19c6a2632', //randomly generated app key
);
//include our models
include_once 'models/TodoItem.php';
//wrap the whole thing in a try-catch block to catch any wayward exceptions!
try {
//*UPDATED*
//get the encrypted request
$enc_request = $_REQUEST['enc_request'];
//get the provided app id
$app_id = $_REQUEST['app_id'];
//check first if the app id exists in the list of applications
if( !isset($applications[$app_id]) ) {
throw new Exception('Application does not exist!');
}
//decrypt the request
$params = json_decode(trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $applications[$app_id], base64_decode($enc_request), MCRYPT_MODE_ECB)));
//check if the request is valid by checking if it's an array and looking for the controller and action
if( $params == false || isset($params->controller) == false || isset($params->action) == false ) {
throw new Exception('Request is not valid');
}
//cast it into an array
$params = (array) $params;
...
...
...
What we’ve done here is actually implement a very simple way of authenticating our front-end clients using a system similar to public-private key authentication. Basically, here is the step-by-step breakdown of how the authentication happens:
Public-key encryption
- an API call is made, in it an $app_id and $enc_request is provided.
- the $enc_request value is the API call parameters, encrypted using
APP KEY. TheAPP KEYis NEVER sent to the server, it’s only used to hash the request. Additionally, the request can only be decrypted using theAPP KEY. - once the API call arrives to the API server, it will check its own list of applications for the
APP IDprovided - when found, the API server attempt to decrypt the request using the key that matches the
APP IDsent - if it was successful in decrypting it, then continue on with the program
Now that the API server is secured with an APP ID and APP SECRET, we can begin programming a front-end client to use the API server.
Step 4: Create the Browser Front-end Client
We’ll begin by setting up a new folder for the front-end client. Create a folder called simpletodo_client_browser on your web server’s folder. When that’s done, create an index.php file and put this code inside:
<!DOCTYPE html>
<html>
<head>
<title>SimpleTODO</title>
<link rel="stylesheet" href="css/reset.css" type="text/css" />
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
<script src="js/jquery.min.js"></script>
<script src="js/jquery-ui-1.8.16.custom.min.js"></script>
<style>
body {
padding-top: 40px;
}
#main {
margin-top: 80px;
text-align: center;
}
</style>
</head>
<body>
<div class="topbar">
<div class="fill">
<div class="container">
<a class="brand" href="index.php">SimpleTODO</a>
</div>
</div>
</div>
<div id="main" class="container">
<form class="form-stacked" method="POST" action="login.php">
<div class="row">
<div class="span5 offset5">
<label for="login_username">Username:</label>
<input type="text" id="login_username" name="login_username" placeholder="username" />
<label for="login_password">Password:</label>
<input type="password" id="login_password" name="login_password" placeholder="password" />
</div>
</div>
<div class="actions">
<button type="submit" name="login_submit" class="btn primary large">Login or Register</button>
</div>
</form>
</div>
</body>
</html>
That should look something like this:
SimpleTODO Login Page
Take note that I’ve included 2 JavaScript files and 2 CSS files here:
- reset.css is your standard CSS reset script. I use the meyerweb.com css reset.
- bootstrap.min.css is the Twitter Bootstrap
- jquery.min.js is the latest jQuery library
- jquery-ui-1.8.16.custom.min.js is the latest jQuery UI library
Next, let’s create the login.php file so we store the username and password inside a session on the client.
<?php
//get the form values
$username = $_POST['login_username'];
$userpass = $_POST['login_password'];
session_start();
$_SESSION['username'] = $username;
$_SESSION['userpass'] = $userpass;
header('Location: todo.php');
exit();
Here, we simply start a session for the user, based on the username and password combination the user will provide. This acts as a simple combination key, which will allow a user to access stored TODO items for a specific combination of both the username and password. We then redirect to todo.php, where we start interacting with the API server. Before we start coding the todo.php file though, let’s first create an ApiCaller class, which will encapsulate all the API calling methods we’ll need, including encrypting the requests.
Create apicaller.php and put the following inside:
<?php
class ApiCaller
{
//some variables for the object
private $_app_id;
private $_app_key;
private $_api_url;
//construct an ApiCaller object, taking an
//APP ID, APP KEY and API URL parameter
public function __construct($app_id, $app_key, $api_url)
{
$this->_app_id = $app_id;
$this->_app_key = $app_key;
$this->_api_url = $api_url;
}
//send the request to the API server
//also encrypts the request, then checks
//if the results are valid
public function sendRequest($request_params)
{
//encrypt the request parameters
$enc_request = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->_app_key, json_encode($request_params), MCRYPT_MODE_ECB));
//create the params array, which will
//be the POST parameters
$params = array();
$params['enc_request'] = $enc_request;
$params['app_id'] = $this->_app_id;
//initialize and setup the curl handler
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->_api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, count($params));
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
//execute the request
$result = curl_exec($ch);
//json_decode the result
$result = @json_decode($result);
//check if we're able to json_decode the result correctly
if( $result == false || isset($result['success']) == false ) {
throw new Exception('Request was not correct');
}
//if there was an error in the request, throw an exception
if( $result['success'] == false ) {
throw new Exception($result['errormsg']);
}
//if everything went great, return the data
return $result['data'];
}
}
We’ll be using the ApiCaller class to send requests to our API server. This way, all the necessary encryption and cURL initialization code will be in one place, and we won’t have to repeat our code.
-
the
__constructfunction takes in three parameters:- $app_id – the
APP IDfor the client (which is APP001 for the browser client) - $app_key – the
APP KEYfor the client (which is 28e336ac6c9423d946ba02d19c6a2632 for the browser client) - $api_url – the URL of the API server, which is
http://localhost/simpletodo_api/
- $app_id – the
-
the
sendRequest()function:- encrypts the request parameters using the
mcryptlibrary in the same manner that the API server decrypts it - generates the
$_POSTparameters to be sent to the API server - executes the API call via cURL
- checks the result of the API call was successful or not
- returns the data when everything went according to plan
- encrypts the request parameters using the
Now, let’s begin with the todo.php page. First off, let’s create some code to retrieve the current list of todo items for the user nikko with the password test1234 (this is the user/password combination we used earlier to test the API server).
<?php
session_start();
include_once 'apicaller.php';
$apicaller = new ApiCaller('APP001', '28e336ac6c9423d946ba02d19c6a2632', 'http://localhost/simpletodo_api/');
$todo_items = $apicaller->sendRequest(array(
'controller' => 'todo',
'action' => 'read',
'username' => $_SESSION['username'],
'userpass' => $_SESSION['userpass']
));
echo '';
var_dump($todo_items);
Go to the index.php page, login as nikko/test1234, and you should see a var_dump() of the TODO item we created earlier.
Congratulations, you’ve successfully made an API call to the API server! In this code, we’ve:
- started the session so we have access to the
usernameanduserpassin the$_SESSION - instantiated a new
ApiCallerclass, giving it theAPP ID,APP KEYand the URL of the API server - send a request via the
sendRequest()method
Now, let’s reformat the data so it looks better. Add the following HTML to the todo.php code. Don’t forget to remove the var_dump()!
<!DOCTYPE html>
<html>
<head>
<title>SimpleTODO</title>
<link rel="stylesheet" href="css/reset.css" type="text/css" />
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="css/flick/jquery-ui-1.8.16.custom.css" type="text/css" />
<script src="js/jquery.min.js"></script>
<script src="js/jquery-ui-1.8.16.custom.min.js"></script>
<style>
body {
padding-top: 40px;
}
#main {
margin-top: 80px;
}
.textalignright {
text-align: right;
}
.marginbottom10 {
margin-bottom: 10px;
}
#newtodo_window {
text-align: left;
display: none;
}
</style>
<script>
$(document).ready(function() {
$("#todolist").accordion({
collapsible: true
});
$(".datepicker").datepicker();
$('#newtodo_window').dialog({
autoOpen: false,
height: 'auto',
width: 'auto',
modal: true
});
$('#newtodo').click(function() {
$('#newtodo_window').dialog('open');
});
});
</script>
</head>
<body>
<div class="topbar">
<div class="fill">
<div class="container">
<a class="brand" href="index.php">SimpleTODO</a>
</div>
</div>
</div>
<div id="main" class="container">
<div class="textalignright marginbottom10">
<span id="newtodo" class="btn info">Create a new TODO item</span>
<div id="newtodo_window" title="Create a new TODO item">
<form method="POST" action="new_todo.php">
<p>Title:<br /><input type="text" class="title" name="title" placeholder="TODO title" /></p>
<p>Date Due:<br /><input type="text" class="datepicker" name="due_date" placeholder="MM/DD/YYYY" /></p>
<p>Description:<br /><textarea class="description" name="description"></textarea></p>
<div class="actions">
<input type="submit" value="Create" name="new_submit" class="btn primary" />
</div>
</form>
</div>
</div>
<div id="todolist">
<?php foreach($todo_items as $todo): ?>
<h3><a href="#"><?php echo $todo->title; ?></a></h3>
<div>
<form method="POST" action="update_todo.php">
<div class="textalignright">
<a href="delete_todo.php?todo_id=<?php echo $todo->todo_id; ?>">Delete</a>
</div>
<div>
<p>Date Due:<br /><input type="text" id="datepicker_<?php echo $todo->todo_id; ?>" class="datepicker" name="due_date" value="12/09/2011" /></p>
<p>Description:<br /><textarea class="span8" id="description_<?php echo $todo->todo_id; ?>" class="description" name="description"><?php echo $todo->description; ?></textarea></p>
</div>
<div class="textalignright">
<?php if( $todo->is_done == 'false' ): ?>
<input type="hidden" value="false" name="is_done" />
<input type="submit" class="btn" value="Mark as Done?" name="markasdone_button" />
<?php else: ?>
<input type="hidden" value="true" name="is_done" />
<input type="button" class="btn success" value="Done!" name="done_button" />
<?php endif; ?>
<input type="hidden" value="<?php echo $todo->todo_id; ?>" name="todo_id" />
<input type="hidden" value="<?php echo $todo->title; ?>" name="title" />
<input type="submit" class="btn primary" value="Save Changes" name="update_button" />
</div>
</form>
</div>
<?php endforeach; ?>
</div>
</div>
</body>
</html>
It should now look something like this:
Pretty cool huh? But this currently does nothing, so let’s begin adding some functionality. I’ll provide the code for new_todo.php, which will call the todo/create API call to create a new TODO item. Creating the other pages (update_todo.php and delete_todo.php) should be very similar to this one, so I’ll leave it up to you to create those. Open up new_todo.php and add the following code:
<?php
session_start();
include_once 'apicaller.php';
$apicaller = new ApiCaller('APP001', '28e336ac6c9423d946ba02d19c6a2632', 'http://localhost/simpletodo_api/');
$new_item = $apicaller->sendRequest(array(
'controller' => 'todo',
'action' => 'create',
'title' => $_POST['title'],
'due_date' => $_POST['due_date'],
'description' => $_POST['description'],
'username' => $_SESSION['username'],
'userpass' => $_SESSION['userpass']
));
header('Location: todo.php');
exit();
?>
As you can see, the new_todo.php page uses the ApiCaller again to facilitate the sending the todo/create request to the API server. This basically does the same thing as before:
- start a session so it has access to the
$usernameand$userpasssaved in the$_SESSION - instantiate a new
ApiCallerclass, giving it theAPP ID,APP KEYand the URL of the API server - send the request via the
sendRequest()method - redirect back to
todo.php
Congratulations, it works! You’ve successfully created an API-centric application!
Conclusion
There are so many advantages to developing an application that’s built around an API. Want to create an Android application version of SimpleTODO? All the functionality you would need is already in the API server, so all you need to do is just create the client! Want to refactor or optimize some of the classes? No problem — just make sure the output is the same. Need to add more functionality? You can do it wihtout affecting any of the client’s code!
Though there are some disadvantages like longer development times or more complexity, the advantages of developing a web application in this manner greatly outweight the disadvantages. It’s up to us to leverage on this kind of development today so we can reap the benefits later on.
Are you planning to use an API server for your next web application, or have you already used the same technique for a project in the past? Let me know in the comments!
Web design is such a broad field that mistakes can be spotted all over the place – it is almost impossible to deliver a product without a mistake until you undergo full testing, which not everybody has the financial power or time to do. These mistakes can range from a few pixels of padding missing to using a wrong number of fonts. Today we’ll take a look at some of the problems people make so that next time you deliver or design a product you can avoid these pitfalls. This way your products will be better overall and your design skills will be appreciated even more.
Let’s begin with the typography. With content being arguably the most important element of a webpage, a designer must have knowledge of how to make it work. Reading some typography books or tutorials is recommended, because it will improve your use of fonts and typefaces and will allow you to play with them for better results. With the right font every piece of text can be made interesting and attractive in web design. Modern designers already know the importance of typography and spend lots of hours testing new typefaces and improving their designs before delivery.
Serif – Sans-serif relation
Mixing typefaces is popular nowadays and works wonders if you know how to make it work. Mixing two different styles can create results that look very good, but pay attention to mixing serif with sans-serif fonts. While you can try your skills doing it, there is a good idea to ask for a second opinion before you propose your client a design with mixed fonts. Typography always looks good to yourself and always expresses the thing you want it to express, but always ask for another opinion. Remember it is rarely about you, but about the future visitors of your webpage.
Number of fonts
There is not much to say here, but the bottom line is don’t mix too many fonts in the same design. Having a couple of fonts to play with is much better than playing with the whole Google Web Fonts suite, because this can, and will, disrupt the readability of your text. As a rule of thumb it is good to use the same font for content all over the webpage, and only use another one for headings, big titles and other elements. Two fonts should be enough for every matter, and keep in mind: never use more than three at a time.
The Gestalt Law of Similarity shows that people tend to group objects together if they look alike. If you wish your content to be part of the same visual field, then don’t use different typefaces, because this will create the opposite effect. The same font provides good continuation to the content as well, which makes it more readable for the user, improving his experience on your webpage.
On the other side, using the same font all over your webpage might be a bit too boring and might look like a beginners work. This is why I said that two is, as a general rule of thumb, the best number of typefaces you can and should combine in your designs. Now don’t get me wrong, I’m not saying this is how it should always be, but I’ve achieved success and good results with this number all the time, so it might be worth it to give it a shot.
The best way to achieve a good result is testing and playing with fonts. I wrote a small guide on how to improve your website’s typography here, take it as a short read.
Contrast is important
Because everybody wants to be different on the internet, some designers develop interfaces using lots of colors – which is not a problem, as long as you use them wisely. Some designers play with too many colors and achieve some nice results at times (at least they think so), that they forget about having a powerful contrast between background and content. This is important because it allows the user to better read the text and doesn’t make his time on your website frustrating.
As you can see in the image below, the text on the left side, written in pure black and white, is easier to read, because it has a high contrast with the background. On the right side you can see that the content is much more difficult to read, although it is the same font type and size as in the left column. Dark grey and red do not have a high contrast with blue, therefore it is not a good choice of colors. Sure, this image shows basic and obvious mistakes and I am sure not many of you thought of using the combinations on the right side, but it is just an image that illustrates what the choice of color can turn your website into.

Now that we settled typography, fonts and colors, let’s move on to spacing. With our screens becoming bigger and bigger, there is a lot of space of play with. We do not surf the web on screens with a low 640 x 800 pixels resolution; we’re doing it on 15″+ screens now and a minimum resolution of 1024 x 768, according to the W3C. Sure, there is still the mobile screen matter, but we will discuss it another time. Right now we focus on design for desktop.
It is always good to give thought to padding, margins and general spacing between elements. This is called “working with negative space”. The best designs out there use a lot of negative space and therefore have a lot of visibility, content is distinguishable from other elements and, with a simple but smart choice of color, they are sustainable and work good on long term for all types of users.
Spacing needs to be kept consistent for it to work well, so always pay attention to the small details when designing or coding – this is a matter of pixels for both internal padding and external margins. The grid layout you decide to build upon in the beginning will help you stick with exact margins, and if you don’t use a grid system, then go and get one from here.
Now I am not saying you should waste a lot of space only because you have it, but having a cluttered design will not help either. If you don’t know where to start from, go out there and visit some webpages you like, I am pretty sure some of them work on a grid system and use a lot of negative space. Take Apple’s website for example (image below). They tend to maximize the use of white space and keep the content on the low side, but without minimizing its importance. There are never problems with hierarchy, everybody knows what is important and what’s less important and all looks organized.
Apple's webpage is a very good example on how to use negative space.
There are more sources out there where you can get a good grid system for every webpage you work on. It’s a very good idea to always build on a framework and keep building on it until you deliver the final product. By using some preset style and elements of margin, padding and spacing, you will make the work easier for you and the final website better in terms of design.
Using old tech
This should be punishable by law. Designers who still use tables (like in the beginning of the 2000′s) and still develop using Microsoft Frontpage should be banned for life. Also, old elements like animated GIFs, background music or frames should be avoided at any cost. All these things are not only out of style, but are not up to the standards of the web anymore. This will make the webpage load slower, get indexed worse or not at all and the new browsers might not even interpret your code accordingly. Technologies appear on the web all the time and it is important for every designer or developer to keep up with them. If you still have old webpages built with these elements, go back now and update them, because otherwise they will only make a bad name for yourself. Although you might aim for their past success, you don’t want to have a website like the one below, do you?
AOL's old website from the 90s shows what you should avoid using today.
Size, placing and proportion
Because now you know what a framework is and you’ve probably already tried it, I will go a bit more in depth. Size and proportion are important elements of a grid system because they tend to show the user what is important and what is not very important. The navigation bar should be placed at the top or in worst case in the sidebar, but it always has to be over the fold, because the user needs to surf around your website. It is also important to make the most important elements bigger without making the others too small. When the user loads your webpage for the first time, he shouldn’t use more than three seconds to find out what’s important there, where the navigation is, if there is a grid system, where is the content, is the content easy to read, does he know where he is in that moment and so on. There are, as you can see, many things a user needs to find out by himself in the first few seconds after he lands on a webpage, therefore aid this process by making these elements clearly stand out from each other.
The items and elements on a webpage should be easy to access. The user should not zoom, squint or attempt to work too much for finding the information he needs. He should only take a brief look and already know what and where to do.
Applied Divine Proportion
If you also heard of Golden Ration or Divine Proportion, you know that most standard designs adhere to it. Although designers deserve some credit for it, the Golden Ratio of 1 to 1.62 in a rounded form is widely used out there in the world. The Divine Proportion helps balance web design in a natural way while keeping everything in balance and make the design feel just right.
Set goals
Before starting on a design, it is always a good idea to decide what your goals are, what you want to achieve and why. Don’t ever forget this afterwards, because setting goals is important for the development process. Forgetting what your goals are will make your design hectic and less friendly. Therefore, if you need to, occasionally go back to your original goals while developing and try to see if everything still matches your ideas, otherwise change what needs to be changed. This way you will ensure your designs will always stay clean and you will always focus on the main goal.
Let’s start discussing!
With so many things to look out for in the design world, I know it is not an easy task to deliver good products, but making an effort will always pay off in the end. Sure, solving these issues might not be that easy in the beginning if you are inexperienced, but if you work on them they will come with time, trust me.
Have you ever made these mistakes, or at least some of them? Did you ever think of a smart way of solving them? Share your thoughts with us and let’s make the design world better for the more inexperienced of us.




