Notes:
- CodeIgniter is MIT licensed which means it’s FREE.
- Here is the website for CodeIgniter https://www.codeigniter.com/
- PHP 5.6 > & mysqli and pdo drivers needed
- This is very lightweight & easy to install.
- Download the latest version from the website. (I’m using 3.1.0)
- Check your current version:
-
echo CI_VERSION;
-
- Unzip & copy the files to your web server
- Set the app url in application/config/config.php
- Set the database parameters in application/config/database.php
- If you want to have more security, change the system and application folders to something else and indicate them in index.php in the root folder. System & application folders should never be accessible to web
- CodeIgniter doesn’t have a template enginer. You’ll need to learn the templating code like blade in Laravel if you want a template enginer. CodeIgniter uses php blocks instead. Although there is a template parser optionally available.
- Application Flow:
- MVC structure but fairly loose approach. You can ignore models & build application using controllers & views.
- CI lets you use existing scripts & it doesn’t require you to use command line.
- URI segments – example.com/class(controller class)/function(class function)/ID (any parameter passed)
- Removing the index.php – http://www.codeigniter.com/user_guide/general/urls.html#removing-the-index-php-file
- create .htaccess file in the root folder and add following code
-
RewriteEngine on
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ index.php/$1 [L]
-
- create .htaccess file in the root folder and add following code
- You can add url suffixes, just to pretend they are .html or .xyz
- Query strings in the URL are also possible – http://www.codeigniter.com/user_guide/general/urls.html
- Controllers: all the controllers are stored in this folder
- Create a file name World.php in the controllers folder
- name the class World similar to the welcome (Welcome.php) controller.
- if you have not removed or redirected index.php, the url you need to access is appurl/index.php/world
- URI segments can be passed to methods:
- example.com/index.php/products/shoes/sandals/123
- public function shoes($sandals, $id) {echo $sandals; echo $id;} will echo Sandals & 123 on the page.
- Default controller – can be set in /application/config/routes.php
- Remapping methods:
- if _remap() exist in the controller, this will be called all the time.
- http://www.codeigniter.com/user_guide/general/controllers.html#remapping-method-calls
- public function _remap($method) { if ($method === ‘show’) { $this->$method(); } else { $this->index(); }}
- return call_user_func_array(array($this, $newmethod), $params); – this is used to send the parameters to a new method.
- output method
- private or protected methods will not be served to the public
- Views:
- views stored in /application/views. Just with .php extension
- called with $this->load->view(“viewname”);
- headers & footers can be put in different views and can be called all at ones in an order.
- Adding data to the views:
- sending data in arrays as parameter to the view. Eg: $this->load->view(‘viewname’, array(“country”=>”Australia”,”city”=>”Melbourne”));
- Calling the variable with key names in the views. Eg: $country, $city
- foreach loops can be used
- Returning data to a string
- Setting the third parameter to “TRUE” will return all the view data to a string.
- Eg: $string=$this->load->view(‘viewname’,”, TRUE);
- View eg:
-
<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″>
<title>My World</title>
<style>
body{
font-family:sans-serif;
}
</style>
</head>
<body>
<section>
<? foreach ($world as $country) {?>
<h3><? echo element(‘country_name’,$country); ?></h3>
<ul>
<? foreach ($country[‘cities’] as $city) { ?>
<li><?= $city[‘city_name’]; ?></li>
<? } ?>
</ul>
<? } ?>
</section>
</body>
</html>
- Models:
- Models work with information in your database
- Model classes will have a function to insert, update and retrieve data from DB
- Models are stored in /application/models/
- Class name should always start with capital letter
- file name must match class name
- Loading model:
- $this->load->model(“model_name”);
- ones the model is loaded, you’ll get access to all methods using an object with the same name as your class.
- $this->model_name->method();
- you can assign a different name to the object with the second parameter. Eg: $this->load->model(“model_name”,”obj_name”);
- Getting results from DB:
- Database parameters needs to be set already in /application/config/database.php or can be manually set using $config[‘database’] etc
- you have to autoload database libraries in /application/config/autoload.php. Eg: $autoload[‘libraries’]=array(‘database’);
- Model code: public function get_all(){
$query=$this->db->get(‘country’);
return $query->result();
} - Controller code: $this->load->model(“World_model”);
$data[‘data’]=$this->World_model->get_all();
$this->load->view(‘worldview’,$data); - View code: <?php foreach ($data as $key => $value) {
echo “<h2>”.$value->name.”</h2>”;
?> - Check all the functions available for Database queries
- Database query builder:
- Using query builder pattern gives a simplified means of retrieving data. Instead of writing the entire query ‘select …’, could use get().
- class World_model extends CI_Model {
public function __construct(){
parent::__construct();
}
public function get_all(){
$query=$this->db->get(‘country’);
$world=[];
foreach ($query->result() as $row)
{
$cities=$this->get_cities($row->country_id);
$world[]=array(‘country_id’=>$row->country_id,
‘country_name’=>$row->name,
‘cities’=>$cities,
‘created_at’=>$row->created_at,
‘updated_at’=>$row->updated_at);
}
return $world;
}
public function get_cities($country_id){
$query=$this->db->get_where(‘city’,array(‘country_id’=>$country_id));
$cities=[];
foreach ($query->result() as $row)
{
$cities[]=array(‘city_id’=>$row->city_id,
‘city_name’=>$row->name,
‘created_at’=>$row->created_at,
‘updated_at’=>$row->updated_at);
}
return $cities;
}
public function get_countries(){
$query=$this->db->get(‘country’);
return $query->result();
}
} - Learn more here http://www.codeigniter.com/user_guide/database/index.html
- Helper functions:
- helpers can be stored in /applications/helpers/ folder
- Multiple helpers can be loaded
- helpers can be autoloaded for global usage
- Once you’ve loaded the Helper File containing the function you intend to use, you’ll call it the way you would a standard PHP function.For example, to create a link using the anchor() function in one of your view files you would do this: <?php echo anchor(‘blog/comments’, ‘Click Here’);?>
- Array Helper
- eg: echo $array_name[‘hello’] can be written as echo element(‘hello’, $array_name);
- http://www.codeigniter.com/user_guide/helpers/index.html
- Using libraries
- for form validation etc. Eg: $this->load->library(‘form_validation’);
- you can create your own libraries & store them in /application/libraries
- You can’t use $this in custom libraries, you need pass the function by reference. Eg: $CI = & get_instance();
- Using CodeIgniter Drivers
- Drivers can be loaded like all $this->load->driver(“driver_name”);
- Stored in libraries folder under driver_name directory
- Core classes can be extended or replaced
- Hookes:
- CodeIgniter’s Hooks feature provides a means to tap into and modify the inner workings of the framework without hacking the core files.
- http://www.codeigniter.com/user_guide/general/hooks.html
- Common functions & compatibility functions
- Password hashing etc functions are compatibility functions
- http://www.codeigniter.com/user_guide/general/compatibility_functions.html
- Routing:
- Wildcard routing
- Setting your own routing rules is possible & it must be defined in /application/config/routes.php, to an array $route.
- Regular expressions:
- Eg: $route[‘products/([a-z]+)/(\d+)’] = ‘$1/id_$2’;
- Call backs:
- Eg: $route[‘products/([a-zA-Z]+)/edit/(\d+)’] = function ($product_type, $id) { return ‘catalog/product_edit/’ . strtolower($product_type) . ‘/’ . $id; };
- Using HTTP verbs –
- Eg:
- $route[‘products’][‘put’] = ‘product/insert’;
- $route[‘products/(:num)’][‘DELETE’] = ‘product/delete/$1’;
- Eg:
- There are few reserved routes like default_controller, 404_override, translate_uri_dashes
- The reserved routes must come before any wildcard or regular expression routes.
- Wildcard routing
- Error handling:
- http://www.codeigniter.com/user_guide/general/errors.html
- Eg: show_error($message, $status_code, $heading = ‘An Error Was Encountered’)
- Error template is in /application/views/errors/html/error_general.php
- Caching:
- performance can be achieved by caching pages
- you can set the time
- Eg: $this->output->cache($n);
- Deleting cache is also possible with a call. Eg: $this->output->delete_cache(‘/foo/bar’);
- Profiler:
- Running with CLI:
- You can call the controllers on command line as well
- Running multiple applications in the same installation is not possible unless you copy all the folders like config, controllers into each sub directory
- Environment:
- By default, CodeIgniter comes with the environment constant set to use the value provided in $_SERVER['CI_ENV'], otherwise defaults to ‘development’. At the top of index.php in roote folder, you will see: define(‘ENVIRONMENT’, isset($_SERVER[‘CI_ENV’]) ? $_SERVER[‘CI_ENV’] : ‘development’);
- Security:
- URIs should only contain the following:
- Alpah-numeric text
- ~, %, ., :, _, -, space
- hash_pbkdf() is for versions of php below 5.5 for password hashing
- URIs should only contain the following:
- Create Form:
My Github Repo:
https://github.com/sainag/CodeIgniter_World