https://github.com/bcit-ci/CodeIgniter
Basic
This time we will learn about one of the php frameworks that are quite popular and very powerful. That is code igniter (CI) . We will not learn from the basic, because there may be many tutorials that have discussed about it. in this tutorial we will learn how to create an API using this framework and we will also learn how to make authentication using the code igniter. Let's getting started..
Because code igniter is a framework, the goal is to simplify and speed up programmers to create a project. to start this tutorial, you must install the code igniter first. in this tutorial I use code igniter 3.
Lets install it first, you can download here. After you have finished downloading you can run Code igniter on your localhost like Xammp, Wammp or etc. after you run it on your local server. we will see the results like the picture below, I put the code in the tutorial-ci folder.
If the image appears, that's means you have successfully installed it, then how can the page appear, let's find out.
What we see above comes from routes.php file, You can see the file directory as shown below.
routes.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
If we look at the code from routes.php, we will see $route['default_controller'] = 'welcome'; this means that if we don't enter any URL, the code igniter will call the default controller, in this code the default controller is 'welcome'.
Then we will go to the controller in the code igniter, we can see the contoller in the controllers folder, we can see as shown below.
Controller welcome.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
$this->load->view('welcome_message');
}
}
Then after the controller welcome is called in routes.php we will see the contents of the welcome controller, as we see in the picture above, in the welcome class class Welcome extends CI_Controller { }, there is anfunction index(){ } inside welcome controller. please note the index() is the default function that will automatically be called in the controller.
In the index function we call $this-> load-> view ('welcome_message');, This means we will call a view with the name welcome_message. We can see the view in the view folder, as shown below.
welcome_message.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to CodeIgniter</title>
<style type="text/css">
::selection { background-color: #E13300; color: white; }
::-moz-selection { background-color: #E13300; color: white; }
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#body {
margin: 0 15px 0 15px;
}
p.footer {
text-align: right;
font-size: 11px;
border-top: 1px solid #D0D0D0;
line-height: 32px;
padding: 0 10px 0 10px;
margin: 20px 0 0 0;
}
#container {
margin: 10px;
border: 1px solid #D0D0D0;
box-shadow: 0 0 8px #D0D0D0;
}
</style>
</head>
<body>
<div id="container">
<h1>Welcome to CodeIgniter!</h1>
<div id="body">
<p>The page you are looking at is being generated dynamically by CodeIgniter.</p>
<p>If you would like to edit this page you'll find it located at:
application/views/welcome_message.php
The corresponding controller for this page is found at:
application/controllers/Welcome.php
If you are exploring CodeIgniter for the very first time, you should start by reading the User Guide.
Page rendered in {elapsed_time} seconds. <?php echo (ENVIRONMENT === '</span><span class="ll-nam">development</span><span class="ll-str">') ? '
CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?></p>
</div>
</body>
</html>
Now we already know how the code igniter comes from and how to structure the folder, so we can conclude it is Routes -> Controller -> View. enough of our introduction with Code Igniter, because in this tutorial we will focus on creating an API. So I won't talk too much about the basics of the Code igniter, we will discuss it in other tutorials.
The first thing we will do configure on our application, we will do the settings in config.php, Because we will focus on the API we don't need the settings in the view or the frontend side.
The following is a snippet from the config.php file.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$config['base_url'] = 'http://localhost:80/tutorial_ci';
$config['index_page'] = ' ';
Create base url: We can make our own base_url specifically for API, so our endpoints will start from http://localhost:80/tutorial_ci/api.
Change root file: Because we will focus on the API we have to change our root, at the fresh download the Code Igniter our root application starts at index.php $config['index_page'] = ' index.php';. Now we will change it to $config['index_page'] = ' ';this means that our root starts from the application.
Create .htaccess: to remove index.php we need to create a .htaccess which is useful for redirecting the file or root after index.php index.php/$1.
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
Because we will only use the code igniter to make the API we only need to use the database library, we can set it on autoload.php like the example below
$autoload['libraries'] = array('database');
next, we will configure it in database.php.The following is the configuration of my database. adjust to your configuration. in this tutorial I use the mysqli driver database 'dbdriver' => 'mysqli'.
database.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'auth_ci',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
In this tutorial I use the 'database' => 'auth_ci', hostname 'hostname' => 'localhost' Username 'username' => 'root' Password 'password' => ' '.
then we will create a database that we have configured in database.php, I will create an auth_ci database.
In this tutorial, I will create an API about authentication, so I will create table users. The following is the structure of the users table.
users.sql
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL,
`email` varchar(250) NOT NULL,
`password` int(250) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
| Name | Type | Length/Value | Index |
|---|---|---|---|
| id | int | 11 | Primary |
| varchar | 250 | -- | |
| password | varchar | 250 | -- |
| updated_at | timestamp | -- | -- |
| created_at | timestamp | -- | -- |
We go back to routes.php, here we will start to make routing for our API. We will make a provision, all of our routing fires will have a fire prefix in the URL, this is commonly used in each endpoint. we can see an example like this
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//Routes
$route['api/users']['GET'] = "UsersController/all_users"; // ENDPOINT to get all users data
$route['api/users/(:num)']['GET'] = "UsersController/detail_user/$1"; // ENDPOINT to detail user
$route['api/register']['POST'] = "UsersController/save"; // ENDPOINT to regsiter new user
$route['api/user/(:num)']['PUT'] = "UsersController/update/$1"; // ENDPOINT to edited/updated user
$route['api/user/(:num)']['DELETE'] = "UsersController/delete/$1"; // ENDPOINT to deleted user
$route['api/login'] = "UsersController/save"; // ENDPOINT to Login
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['api/users'] and then the method used ['GET'], after that we can initialize the controller we use and the method "UsersController/all_users";.Example:
$route['URLendpoint']['METHOD'] = "Controllers/method";
(:num), to pass parameters that do not provide specific types you can use (:any). then we will accept these parameters in the controller in this way "UsersController/detail_user/$1";Example:
$route['api/users/(:num)']['GET'] = "UsersController/detail_user/$1";
In routes.php we have made several types of methods and their uses, we have learned how to do the settings in the Code igniter to make it a RESTful API. In the next tutorial, we will start making the RESTful API for the authentication system. I hope this tutorial can explain you to start making RESTful API.