Currency Conversion library in CodeIgniter

By

October 16, 2012Code IgniterNo comments

To understand this tutorial user must be aware of MVC (Model-View-Controller) concepts & workflows. Converting currency is pretty simple with CodeIgniter in this page we are going to see the following,

  1. How to write currency converter library
  2. How to call the library in the controller
  3. How to interact with Database and Views

View demo Download source

As the first step to create a library, navigate your folder to

application\libraries

Under the above shown folder create a file called “currency_converter.php” which is the library file going to be called in controller later. These library going to have 4 variables in it,

Constructor function has to be written to transport the parameters to the library as shown below,

Business logic function has to be created separately to handle each and every request like below,

After creating library navigate to

application\controllers

Under the above shown folder create a file called “currencies.php” which is the controller file. In the controller file have two main functions 1 is for loading the default index and another is for converting & displaying the given input. In the controller you can call the library by using below code,

To show the result from the library,

Now before displaying the result you need to show the list of countries in the form to convert easily. So need to create a table containing country code and country name. Mysql syntax for creating table is given below,

SQl dump for data to be inserted is given in the attachment. Now we have to create a model class for interacting with database and controller.

After creating controller navigate to

application\models

Under the above shown folder create a file called “currenciesmodel.php” which is the model file. In the model file have two main functions 1 is for default constructor and another is for getting the result from the table.¬†For loading the database class in the model use the below code, its because sometime the error will raise like “$db is called on non-object” to avoid this load the database class in the constructor,

The second function should fetch the table result from the database function is as shown below,

In the controller you can call the model with below code snippets,

After creating controller navigate to

application\views

Under the above shown folder create a file called “currency_converter.php” which is the view file. In the view file you can access all the data array passed on controller file, the way to include the view file is shown below.

Once all these setup has been done you can see the output in the browser as below,

View demo Download source

Leave a Reply