Coding a simple Web API with CodeIgniter – Part 2

Now that we have a working installation of CodeIgniter let’s take a closer look at the core of our Web API functionality: the controller.

In CodeIgniter we define a controller as a file inside the controller directory by using the following template.

You can find all the code in this GitHub repository.

Note that the class name must match the file name and the first letter must be uppercase. Also take in account the reserved names used by the framework.

In the previous post we saw how to call methods of the API via URL’s and we also implemented a simple way to output data via echo in the fake db controller. The next step is to know how to pass parameters to these methods.

You can do so by:

  • Using URI segments as parameters
  • Including POST parameters in an http request
  • Including get information in the URL

Let’s see these in action. Make a new subfolder inside controllers/ called examples/, inside create a inputs.php file, and place the following code.

As you see the input class is a CodeIgniter library that allows us to do easily grab parameters. This library, among others, is initialized automatically by CodeIgniter. Then you have helpers, helpers differ from libraries in that a helper is just a set of functions with no access to the caller context ($this). Lastly you have drivers, which is a convenient way of relating classes.

For the next example let’s test the inputs controller we just created. As you can see in the following code we are leveraging on the unit testing CodeIgniter library which we need to load manually. Also the url helper will allow us to access the $config['base_url'] configuration that we specified in the previous post. Now create a controllers/test/ folder, place the .php and just call the controller name in your browser.  The index method will be automagically executed and you should see a nice unit testing report telling you that, hopefully, everything is okay.

Let’s create our own helper. A custom helper has to be located in the php/helpers directory and needs to be prefixed with ‘my_’. Let’s call it my_helper.php and copy the following code.

For convenience let’s refactor some configuration parameters, create a myConfig.php file and place it inside php/config/ with the following content changing the database constants accordingly.

And here is the code for the controller.

As you can see we are loading our helper and expecting that tableName, dbName, primaryKey and data are supplied as POST parameters. It shouldn’t be too troublesome to understand how the code is doing its stuff.

Last but not least, if you are an Ext JS or Touch guy you should have an idea about how to leverage an Web API in your application. In the dynamic grid post you can now see clearly how this API is used; CRUD operations mapped inside the proxy and getTableMetadata as the url of an Ext.Ajax request.

Acerca de

Ver todas las entradas de