S
Sppeeaakkeerr::
P
Our Agenda
Our Agenda
➢
➢ What is CodeIgniter ?What is CodeIgniter ? ➢
➢ What makes CodeIgniter a smart framework to use?What makes CodeIgniter a smart framework to use? ➢
➢ Why MVC?Why MVC? ➢
➢ Routing BasicsRouting Basics ➢
➢ Installation and ConfigurationInstallation and Configuration ➢
➢ Model View ControllerModel View Controller ➢
➢ Template IntegrationTemplate Integration ➢
What is CodeIgniter ?
What is CodeIgniter ?
➢
➢ A proven, agile & open PHP web application frA proven, agile & open PHP web application frameworkamework ➢
➢ Enables developers to build web Enables developers to build web applications fasterapplications faster ➢
➢ Offers many helpful code libraries and helpersOffers many helpful code libraries and helpers ➢
➢ Based on MVC design patternBased on MVC design pattern ➢
What makes CodeIgniter a smart
What makes CodeIgniter a smart
framework?
framework?
➢
➢ Exceptional performanceExceptional performance ➢
➢ MVC approach to developmentMVC approach to development ➢
➢ Generates search engine friendly clean URLsGenerates search engine friendly clean URLs ➢
➢ Easily extensibleEasily extensible ➢
➢ Runs on both PHP 4 (4.3.2+) and 5Runs on both PHP 4 (4.3.2+) and 5 ➢
➢ Support for most major databases including MySQL (4.1+), MySQLi, MS SQL, Postgres, Oracle, SQLite, and ODBC.Support for most major databases including MySQL (4.1+), MySQLi, MS SQL, Postgres, Oracle, SQLite, and ODBC. ➢
➢ Application security is a focusApplication security is a focus ➢
➢ Easy caching operationsEasy caching operations ➢
➢ Many libraries and helpers to help you with Many libraries and helpers to help you with complex operations such as email, image manipulation,form validation etccomplex operations such as email, image manipulation,form validation etc ➢
Why MVC?
Why MVC?
➢
➢ MVC stands for Model, View, ControllerMVC stands for Model, View, Controller
➢
➢ Model:Model: The model deals with the raw data and The model deals with the raw data and
database interaction. Component is not required and database interaction. Component is not required and can be included in the controller.
can be included in the controller.
➢
➢ View:View: The view deals with displaying the data and The view deals with displaying the data and
interface controls to the user. interface controls to the user.
➢
➢ Controller:Controller: The controller acts as the in between ofThe controller acts as the in between of
view and model.The controller is the place to load view and model.The controller is the place to load libraries and helpers.
Routing Basics
Routing Basics
Installation
Installation
and
and
Configuration
Configuration
[Download CodeIgniter
Download CodeIgniter
➢
➢ Download CodeIgniter and upload it to your server.Download CodeIgniter and upload it to your server.
http://ellislab.com/codeigniter/download http://ellislab.com/codeigniter/download
➢
CI Directory Structure
CI Directory Structure
➢
➢ TheTheapplicationapplication directory contains model,view,controller,helper,ldirectory contains model,view,controller,helper,library and so ibrary and so on.on. ➢
➢ TheThesystemsystemdirectory is the core and consists of directory is the core and consists of the core framework files. When a new version is the core framework files. When a new version is released, you can updatereleased, you can update
your existing application just by replacing this system directory with
your existing application just by replacing this system directory with the latest release.the latest release.
➢
➢ TheTheuser_guideuser_guide houses the user guide to CI. houses the user guide to CI. ➢
➢
➢ TheThecachecache folder stores all folder stores all the caches generated by the caching library.the caches generated by the caching library.
➢
➢ ThisThisconfigconfig directory includes settings/configuration related information like directory includes settings/configuration related information like database settings, route information etc.database settings, route information etc.
➢
➢ TheThecorecore directorydirectoryneeded to extend the functionality of core classes like controller,loader,router etc.needed to extend the functionality of core classes like controller,loader,router etc.
➢
➢ TheTheerrorserrors folder stores all the template error pages for folder stores all the template error pages for the application.the application.
➢
➢ TheThehelpershelpers folder stores all the helpers which are specific to folder stores all the helpers which are specific to your application like email, imageMagick etc.your application like email, imageMagick etc.
➢
➢ TheThehookshooks folder is for hooks which modify the functioning of folder is for hooks which modify the functioning of CI’s core files.CI’s core files.
➢
➢ TheThelanguagelanguage folder stores lines of text which can be folder stores lines of text which can be loaded through the language library to create multilingual sites.loaded through the language library to create multilingual sites.
➢
➢ TheThelibrarieslibraries folder stores all the libraries folder stores all the libraries which are specific to your application.which are specific to your application.
➢
➢ TheThethird_partythird_party directory will directory will include library files, but only those, which are include library files, but only those, which are imported from third-party.imported from third-party.
Application Directory Structure
Application Directory Structure
➢
➢ TheThedatabasedatabase folder stores all the database drivers and folder stores all the database drivers and class which enable you to connect to database.class which enable you to connect to database. ➢
➢ TheThefontsfonts folder stores all the folder stores all the fonts which can be used by the image manipulation library.fonts which can be used by the image manipulation library. ➢
➢ TheThehelpershelpers folder stores all of folder stores all of CI’s core helpers but you can place CI’s core helpers but you can place your own helpers in here which can be your own helpers in here which can be accessed by allaccessed by all
of your applications.
of your applications.
➢
➢ TheThelanguagelanguage folder stores all of CI’s core folder stores all of CI’s core language files which its libraries and helpers use.language files which its libraries and helpers use. ➢
➢ TheThelibrarieslibraries folder stores all of CI’s core libraries but you can place your own libraries.folder stores all of CI’s core libraries but you can place your own libraries.
System Directory Structure
System Directory Structure
Configuration
Configuration
➢
➢ Need to set upNeed to set up “base_url” “base_url”..
To do this, open up
To do this, open upsystem/application/config/config.phpsystem/application/config/config.php
➢
➢ Need to set up “Need to set up “databasedatabase””
To use a database, open up
Testing CodeIgniter
Testing CodeIgniter
C
C
o
o
n
n
g
g
r
r
a
a
t
t
u
u
l
l
a
a
t
t
i
i
o
o
n
n
,
,
y
y
o
o
u
u
c
c
o
o
n
n
f
f
i
i
g
g
u
u
r
r
e
e
d
d
C
C
o
o
d
d
e
e
I
I
g
g
n
n
i
i
t
t
e
e
r
r
s
s
u
u
c
c
c
c
e
e
s
s
s
s
f
f
u
Model
Model
View
View
Controller
Controller
[What is a controller?
What is a controller?
A Controller is simply a class file that is named in a way that can be associated with a URI. A Controller is simply a class file that is named in a way that can be associated with a URI. http://localhost/news_system/index.php/
http://localhost/news_system/index.php/newsnews
Here CI will find
Here CI will find news.phpnews.php Controller Controller
class News extends CI_Controller {
class News extends CI_Controller {
public function __construct()
public function __construct()
{ { parent::__construct(); parent::__construct(); $this->load->model('news_model'); $this->load->model('news_model'); } }
public function index()
public function index()
{
{
$data['news'] = $this->news_model->get_news();
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
$data['title'] = 'News archive';
$this->load->view('templates/header', $data); $this->load->view('templates/header', $data); $this->load->view('news/index', $data); $this->load->view('news/index', $data); $this->load->view('templates/footer'); $this->load->view('templates/footer'); } } } }
Let's create a simple news controller so you can
Let's create a simple news controller so you can see it in action.see it in action.Then save the fileThen save the file““news.php”news.php”toto““application/controllers/”application/controllers/”folder.folder.
Class names must start with an Class names must start with an uppercase letter.
uppercase letter.
Important Note:
Passing URI segments to function
Passing URI segments to function
http://localhost/news_system/index.php/news/view/
http://localhost/news_system/index.php/news/view/initializing-the-classinitializing-the-class
class News extends
class News extends CI_ControlCI_Controller { ler {
public functi
public function __conston __construct()ruct()
{ { parent::__construct(); parent::__construct(); } } } }
CI allow to pass more t
CI allow to pass more than one segmentshan one segments function name
function name
Class Constructors
Class Constructors
If you intend to use aIf you intend to use a constructor in Controllers,constructor in Controllers,MUSTMUST place place
parent::__construct(); parent::__construct();
Constructors are useful if you need to set
Constructors are useful if you need to set some default values, or runsome default values, or run
a default process when your class is instantiated.
What is a Model?
What is a Model?
Models are PHP classes that are designed to work
Models are PHP classes that are designed to work with information in your database.with information in your database.
Basic prototype for News model class:
Basic prototype for News model class:
class News_model extends CI_Model { class News_model extends CI_Model { public function __construct() public function __construct() {{
$this->load->database(); $this->load->database(); }}
}}
Class names must have the first Class names must have the first letter capitalized
letter capitalized
File name will be lower
File name will be lower case versioncase version of class name i
of class name i.e news_model.php.e news_model.php I Immppoorr t taann t t N Noo t tee
Loading a Model
Loading a Model
$this->load->model('Model_name'); $this->load->model('Model_name');Use a Model
Use a Model
$this->Model_name->method(); $this->Model_name->method();Active Record Class
Active Record Class
➢
➢ CodeIgniter uses a modified version of the Active Record Database Pattern.CodeIgniter uses a modified version of the Active Record Database Pattern. ➢
➢ Pattern allows information to bePattern allows information to beretrievedretrieved,,insertedinserted, and, andupdatedupdated in your database with in your database with minimal scripting.minimal scripting. ➢
Build SQL Select statement
Build SQL Select statement
➢
➢ $query =$query =$this->db->get$this->db->get('mytable');('mytable');
// Produces: SELECT * FROM mytable
// Produces: SELECT * FROM mytable
➢
➢ The second and third parameters enable you to set a The second and third parameters enable you to set a limit and offset clause:limit and offset clause:
$query =
$query =$this->db->get$this->db->get('mytable', 10, 20);('mytable', 10, 20);
// Produces: SELECT * FROM mytable LIMIT 20, 10
// Produces: SELECT * FROM mytable LIMIT 20, 10
➢
➢ $query =$query =$this->db->get_where$this->db->get_where('mytable', array('id' => $id), $limit, $offset);('mytable', array('id' => $id), $limit, $offset);
// Produces: SELECT * FROM mytable where id=$id LIMIT $offset, $limit
// Produces: SELECT * FROM mytable where id=$id LIMIT $offset, $limit
➢
➢ $this->db->select$this->db->select('title, content, date');('title, content, date');
$query =
$query = $this->db->get('m$this->db->get('mytable');ytable');
// Produces: SELECT title, content, date FROM mytable
➢
➢ $this->db->select_max$this->db->select_max('age', ('age', 'member_age'member_age');');
$query =
$query = $this->db->get('m$this->db->get('members');embers'); // Produces: SELECT MAX(age) as
// Produces: SELECT MAX(age) as member_age FROM membersmember_age FROM members
➢
➢ $this->db->order_by$this->db->order_by('title desc, name asc');('title desc, name asc');
// Produces: ORDER BY title DESC, name ASC // Produces: ORDER BY title DESC, name ASC
➢
➢ $names = array('Frank', 'Todd', 'James');$names = array('Frank', 'Todd', 'James');
$this->db->where_in
$this->db->where_in('username', $names);('username', $names); // Produces: WHERE username IN ('Frank',
// Produces: WHERE username IN ('Frank', 'Todd', 'James')'Todd', 'James')
Build SQL Select statement
Build SQL Select statement
➢
➢ $data $data = array( = array( 'title' 'title' => => 'My 'My title' , title' , 'name' 'name' => => 'My 'My Name' Name' , , 'date' 'date' => => 'My 'My date');date');
$this->db->insert
$this->db->insert('mytable', $data);('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date') // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
➢
➢ $this->db->set$this->db->set('name', $name);('name', $name);
$this->db->insert('mytable'); $this->db->insert('mytable'); // Produces: INSERT INTO mytable
// Produces: INSERT INTO mytable (name) VALUES ('{$name}')(name) VALUES ('{$name}') OR
OR
$array = array('name' => $name); $array = array('name' => $name); $this->db->set($array);
$this->db->set($array); $this->db->insert('mytable'); $this->db->insert('mytable');
//You can also pass an associative array
//You can also pass an associative array to this functionto this function
Build SQL Insert statement
Build SQL Insert statement
➢
➢ $data = array('title' => $title,'name' => $name,'date' => $date);$data = array('title' => $title,'name' => $name,'date' => $date);
$this->db->where('
$this->db->where('id', id', $id);$id); $this->db->update
$this->db->update('mytable', $data);('mytable', $data); // Produces:
// Produces:
// UPDATE mytable SET title =
// UPDATE mytable SET title = '{$title}', name = '{$name}', date = '{$date}' WHERE id = '{$title}', name = '{$name}', date = '{$date}' WHERE id = $id$id
➢
➢ $data = array($data = array(
array('title' => 'M
array('title' => 'My title','name' =y title','name' => 'My Name > 'My Name 2' ,'date' => 2' ,'date' => 'My date 2' 'My date 2' ),), array('title' => 'Another title'
array('title' => 'Another title' ,'name' => 'An,'name' => 'Another Name 2' ,'date' other Name 2' ,'date' => 'Another date 2' => 'Another date 2' )) );
);
$this->db->update_batch
$this->db->update_batch('mytable', $data, 'title');('mytable', $data, 'title'); // Produces:
// Produces:
// UPDATE `mytable` SET `name`
// UPDATE `mytable` SET `name` = CASE WHEN `title` = 'My titl= CASE WHEN `title` = 'My titl e' THEN 'My Name 2' WHEN `title` = e' THEN 'My Name 2' WHEN `title` = 'Another title' THEN 'Another Name 2' ELSE'Another title' THEN 'Another Name 2' ELSE `name` END,
`name` END, `date` = CASE WHEN `title` = 'My title' THEN 'My date 2' WHEN `title` = 'Another title' THEN 'Another date 2' ELSE `date` END WHERE`date` = CASE WHEN `title` = 'My title' THEN 'My date 2' WHEN `title` = 'Another title' THEN 'Another date 2' ELSE `date` END WHERE `title` IN ('My title','Another title')
`title` IN ('My title','Another title')
Build SQL Update statement
Build SQL Update statement
➢
➢ $this->db->delete$this->db->delete('mytable', array('id' => $id));('mytable', array('id' => $id));
// Produces: // Produces:
// DELETE FROM mytable WHERE id = $id // DELETE FROM mytable WHERE id = $id
➢ ➢ $this->db->from('mytable');$this->db->from('mytable'); $this->db->truncate $this->db->truncate();(); // or // or $this->db->truncate
$this->db->truncate('mytable');('mytable'); // Produce:
// Produce:
// TRUNCATE mytable // TRUNCATE mytable
Build SQL Delete statement
Build SQL Delete statement
Note: If the TRUNCATE command isn't
Note: If the TRUNCATE command isn't
available, truncate() will execute as
available, truncate() will execute as "DELETE"DELETE
FROM table".
What is View?
What is View?
➢
➢ A view is a A view is a web page, or a page fragment, like a web page, or a page fragment, like a header, footer, sidebar,header, footer, sidebar,
etc. etc.
➢
➢ Views are never called directly, they must be loaded by Views are never called directly, they must be loaded by a controllera controller
Loading a View Loading a View $this->load->view('name'); $this->load->view('name'); <html> <html> <head> <head> <title>My Blog</title> <title>My Blog</title> </head> </head> <body> <body> <h1>Welcome to my Blog!</h1> <h1>Welcome to my Blog!</h1> </body> </body> </html> </html>
Helper
Helper
➢
➢ Helpers means “help you with tasks”.Helpers means “help you with tasks”. ➢
➢ Each helper file is simply a Each helper file is simply a collection of functions or methods.collection of functions or methods. ➢
➢ Stored in yourStored in your system/helperssystem/helpers, or, or application/helpersapplication/helpers directorydirectory
Few common Helpers are listed below:
Few common Helpers are listed below:
➢
➢ URL HelpersURL Helpers, that assist in creating links, that assist in creating links ➢
➢ Form HelpersForm Helpers that help you create that help you create form elementsform elements ➢
➢ Text HelpersText Helpers perform various text formatting routines perform various text formatting routines ➢
➢ Cookie HelpersCookie Helpers set and read cookies set and read cookies ➢
➢ File HelpersFile Helpers help you deal with files help you deal with files
Loading a Helper
Loading a Helper
$this->load->helper('name');
$this->load->helper('name');
Template Integration
Template Integration
[
Where we put
Where we put
css/js/image
css/js/image
directory ?
directory ?
➢
➢ Local CI DirectoryLocal CI Directory “news_system”“news_system” ➢
➢ ConfigureConfigure “base_url““base_url“ & define one more variable & define one more variable “BASE_URI”“BASE_URI”
To do this, open up
To do this, open upsystem/application/config/config.phpsystem/application/config/config.php
➢
Create templates directory
Create templates directory
➢
➢ Create aCreate a“templates”“templates” directory directory
To do this, open up
To do this, open upapplication/views/application/views/
➢
Link to
Link to
css/js/images
css/js/images
➢
➢ ForFor “css”“css” directory directory
<link rel="stylesheet" href="<?php echo BASE_URI; ?>css/layout.css" type="text/css" /> <link rel="stylesheet" href="<?php echo BASE_URI; ?>css/layout.css" type="text/css" />
➢
➢ ForFor “js”“js” directory directory
<script src="<?php echo BASE_URI; ?>js/jquery.js" ></script> <script src="<?php echo BASE_URI; ?>js/jquery.js" ></script>
➢
➢ ForFor “image”“image”directorydirectory
<img src="<?php echo BASE_URI; ?>images/image.jpg" alt="text" /> <img src="<?php echo BASE_URI; ?>images/image.jpg" alt="text" />
Testing of template integration
Testing of template integration
C
C
o
o
n
n
g
g
r
r
a
a
t
t
u
u
l
l
a
a
t
t
i
i
o
o
n
n
,
,
y
y
o
o
u
u
i
i
n
n
t
t
e
e
g
g
r
r
a
a
t
t
e
e
d
d
t
t
e
e
m
m
p
p
l
l
a
a
t
t
e
e
s
s
u
u
c
c
c
c
e
e
s
s
s
s
f
f
u
u
l
l
l
Template Engine
Template Engine
[
Template Engine
Template Engine
➢
➢ Template Parser Class enables you to parse pseudo-variables contained withinTemplate Parser Class enables you to parse pseudo-variables contained within
your view files.
your view files.
Initializing the Class
Initializing the Class
➢
➢ Initialized in your controllerInitialized in your controller
$this->load->library(‘parser’); $this->load->library(‘parser’);
Pass data to view using
Pass data to view using
$this->parser->parse()$this->parser->parse()➢
➢ Method accepts a template name and data Method accepts a template name and data array as inputarray as input
$data=array( ‘news_title’=>’My News, ‘news_heading’=>’My News
$data=array( ‘news_title’=>’My News, ‘news_heading’=>’My News heading’);heading’); $this->parser->parse(‘news_template’,$data);
$this->parser->parse(‘news_template’,$data);
The Template Parser Class is not a full-blown
The Template Parser Class is not a full-blown
template parsing solution.
template parsing solution.
<html> <html> <head> <head> <title>
<title>{news_title}{news_title}</title></title> </head> </head> <body> <body> <h1> <h1>{news_heading}{news_heading}</h1></h1> <p> <p>{news_body}{news_body}</p></p> </body> </body> </html> </html> P P s s e
e u u
d
d o o
-
- v v a a
r
r i i a a
b
b l l e e
l
l o o o o
k k l l i i k k e e t t h h i i s s