SlideShare uma empresa Scribd logo
1 de 47
CodeIgniter & MVC
Jamshid Hashimi
Trainer, Cresco Solution
http://www.jamshidhashimi.com
jamshid@netlinks.af
@jamshidhashimi
ajamshidhashimi
Afghanistan Workforce
Development Program
Agenda
• Supported Features
• Understanding MVC
• Application Flow Chart
• CodeIgniter URLS
• CodeIgniter Controllers
• Views
• Models
• Helpers
• Libraries
• Hooks
Supported Feaures
• Model-View-Controller Based System
• Extremely Light Weight
• Full Featured database classes with support for several platforms.
• Active Record Database Support
• Form and Data Validation
• Security and XSS Filtering
• Session Management
• Email Sending Class. Supports Attachments, HTML/Text email,
multiple protocols (sendmail, SMTP, and Mail) and more.
• Image Manipulation Library (cropping, resizing, rotating, etc.).
Supports GD, ImageMagick, and NetPBM
Supported Feaures
• File Uploading Class
• FTP Class
• Localization
• Pagination
• Data Encryption
• Benchmarking
• Full Page Caching
• Error Logging
• Application Profiling
• Calendaring Class
• User Agent Class
Supported Feaures
• Zip Encoding Class
• Template Engine Class
• Trackback Class
• XML-RPC Library
• Unit Testing Class
• Search-engine Friendly URLs
• Flexible URI Routing
• Support for Hooks and Class Extensions
• Large library of "helper" functions
Understanding MVC
• CodeIgniter is based on the Model-View-
Controller development pattern. MVC is a
software approach that separates application
logic from presentation.
– The Model represents your data structures.
– The View is the information that is being presented to
a user.
– The Controller serves as an intermediary between the
Model, the View, and any other resources needed to
process the HTTP request and generate a web page.
Application Flow Chart
CodeIgniter URLS
• By default, URLs in CodeIgniter are designed
to be search-engine and human friendly.
• CodeIgniter uses a segment-based approach.
example.com/news/article/my_article
CodeIgniter URLS
• The first segment represents the controller class
that should be invoked.
• The second segment represents the class
function, or method, that should be called.
• The third, and any additional segments,
represent the ID and any variables that will be
passed to the controller.
example.com/class/function/ID
CodeIgniter URLS
• Removing index.php
RewriteEngine on
RewriteCond $1 !^(index.php|images|robots.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
DEMO
CodeIgniter Controllers
• A Controller is simply a class file that is named
in a way that can be associated with a URI.
• When a controller's name matches the first
segment of a URI, it will be loaded.
<?php
class Blog extends CI_Controller {
public function index()
{
echo 'Hello World!';
}
}
?>
CodeIgniter Controllers
• The second segment of the URI determines
which function in the controller gets called.
<?php
class Blog extends CI_Controller {
public function index()
{
echo 'Hello World!';
}
public function comments()
{
echo 'Look at this!';
}
}
?>
CodeIgniter Controllers
• If your URI contains more then two segments
they will be passed to your function as
parameters.
<?php
class Products extends CI_Controller {
public function shoes($sandals, $id)
{
echo $sandals;
echo $id;
}
}
?>
CodeIgniter Controllers
• Constructors are useful if you need to set
some default values, or run a default process
when your class is instantiated. Constructors
can't return a value, but they can do some
default work.
<?php
class Blog extends CI_Controller {
public function __construct()
{
parent::__construct();
// Your own constructor code
}
}
?>
DEMO
Views
• A view is simply a web page, or a page
fragment, like a header, footer, sidebar, etc. In
fact, views can flexibly be embedded within
other views (within other views, etc., etc.) if
you need this type of hierarchy.
$this->load->view('view.php');
Views
• CodeIgniter will intelligently handle multiple
calls to $this->load->view from within a
controller.
<?php
class Page extends CI_Controller {
function index()
{
$data['page_title'] = 'Your title';
$this->load->view('header');
$this->load->view('menu');
$this->load->view('content', $data);
$this->load->view('footer');
}
}
?>
Views
• Data is passed from the controller to the view
by way of an array or an object in the second
parameter of the view loading function.
$data = array(
'title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message'
);
$this->load->view('blogview', $data);
Views
• The data array you pass to your view files is
not limited to simple variables. You can pass
multi dimensional arrays, which can be
looped to generate multiple rows.
<?php
class Blog extends CI_Controller {
function index()
{
$data['todo_list'] = array('Clean House', 'Call Mom', 'Run
Errands');
$data['title'] = "My Real Title";
$data['heading'] = "My Real Heading";
$this->load->view('blogview', $data);
}
}
?>
Views
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<h1><?php echo $heading;?></h1>
<h3>My Todo List</h3>
<ul>
<?php foreach ($todo_list as $item):?>
<li><?php echo $item;?></li>
<?php endforeach;?>
</ul>
</body>
</html>
DEMO
Models
• Models are PHP classes that are designed to
work with information in your database.
class Model_name extends CI_Model {
function __construct()
{
parent::__construct();
}
}
Models
$this->load->model('Model_name');
$config['hostname'] = "localhost";
$config['username'] = "myusername";
$config['password'] = "mypassword";
$config['database'] = "mydatabase";
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
DEMO
Helpers
• Helpers, as the name suggests, help you with
tasks. Each helper file is simply a collection of
functions in a particular category.
• Unlike most other systems in CodeIgniter,
Helpers are not written in an Object Oriented
format. They are simple, procedural functions.
Each helper function performs one specific
task, with no dependence on other functions.
Helpers
$this->load->helper('url');
$this->load->helper( array('helper1',
'helper2', 'helper3') );
<?php echo anchor('blog/comments', 'Click
Here');?>
Helpers
• Extending Helpers
– To "extend" Helpers, create a file in your
application/helpers/ folder with an identical name
to the existing Helper, but prefixed with MY_
– The term "extend" is used loosely since Helper
functions are procedural and discrete and cannot
be extended in the traditional programmatic
sense.
DEMO
Libraries
• All of the available libraries are located in your
system/libraries folder.
$this->load->library('class name');
$this->load->library(array('email', 'table'));
Libraries
• CodeIgniter permits your libraries to extend
native classes if you simply need to add some
functionality to an existing library. Or you can
even replace native libraries just by placing
identically named versions in your
application/libraries folder.
– You can create entirely new libraries.
– You can extend native libraries.
– You can replace native libraries.
Libraries
• File names must be capitalized. For example:
Myclass.php
• Class declarations must be capitalized. For
example: class Myclass
• Class names and file names must match.
Libraries
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Someclass {
public function some_function()
{
}
}
/* End of file Someclass.php */
$this->load->library('someclass');
$this->someclass->some_function();
Libraries
• You can use class constructor for initializing
data
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Someclass {
public function __construct($params)
{
// Do something with $params
}
}
?>
Libraries
• Utilizing CodeIgniter Resources
$CI =& get_instance();
$CI->load->helper('url');
$CI->load->library('session');
$CI->config->item('base_url');
etc.
Libraries
• Replacing Native Libraries with Your Versions
– To use this feature you must name the file and the
class declaration exactly the same as the native
library.
– Note that most native classes are prefixed with
CI_.
class CI_Email {
}
Libraries
• If all you need to do is add some functionality to
an existing library - perhaps add a function or two
- then it's overkill to replace the entire library
with your version. In this case it's better to simply
extend the class. Extending a class is nearly
identical to replacing a class with a couple
exceptions:
– The class declaration must extend the parent class.
– Your new class name and filename must be prefixed
with MY_
Libraries
• The parent constructor must be called,
whenever we want to have to use a
constructor in our own library.
class MY_Email extends CI_Email {
public function __construct()
{
parent::__construct();
}
}
Libraries
• Setting your own prefix
– To set your own sub-class prefix, open your
application/config/config.php file and look for this
item:
$config['subclass_prefix'] = 'MY_';
DEMO
Hooks
• CodeIgniter's Hooks feature provides a means
to tap into and modify the inner workings of
the framework without hacking the core files.
– For example, you might want to run a script right
before your controllers get loaded, or right after,
or you might want to trigger one of your own
scripts in some other location.
$config['enable_hooks'] = TRUE;
Hooks
• Hooks are defined in
application/config/hooks.php file. Each hook
is specified as an array with this prototype:
$hook['pre_controller'] = array(
'class' => 'MyClass',
'function' => 'Myfunction',
'filename' => 'Myclass.php',
'filepath' => 'hooks',
'params' => array('milk', 'tea', 'fruit')
);
Hooks
• class The name of the class you wish to invoke. If you prefer to use
a procedural function instead of a class, leave this item blank.
• function The function name you wish to call.
• filename The file name containing your class/function.
• filepath The name of the directory containing your script. Note:
Your script must be located in a directory INSIDE your application
folder, so the file path is relative to that folder. For example, if your
script is located in application/hooks, you will simply use hooks as
your filepath. If your script is located in application/hooks/utilities
you will use hooks/utilities as your filepath. No trailing slash.
• params Any parameters you wish to pass to your script. This item is
optional.
Hooks
• Hook Points
– pre_system: Called very early during system execution.
Only the benchmark and hooks class have been loaded at
this point. No routing or other processes have happened.
– pre_controller: Called immediately prior to any of your
controllers being called. All base classes, routing, and
security checks have been done.
– post_controller_constructor: Called immediately after
your controller is instantiated, but prior to any method
calls happening.
– post_controller: Called immediately after your controller is
fully executed.
Hooks
– display_override: Overrides the _display() function, used
to send the finalized page to the web browser at the end
of system execution. This permits you to use your own
display methodology. Note that you will need to reference
the CI superobject with $this->CI =& get_instance() and
then the finalized data will be available by calling $this->CI-
>output->get_output()
– cache_override: Enables you to call your own function
instead of the _display_cache() function in the output
class. This permits you to use your own cache display
mechanism.
– post_system: Called after the final rendered page is sent
to the browser, at the end of system execution after the
finalized data is sent to the browser.
DEMO
QUESTIONS?

Mais conteúdo relacionado

Mais procurados

Testing Spring Boot Applications
Testing Spring Boot ApplicationsTesting Spring Boot Applications
Testing Spring Boot ApplicationsVMware Tanzu
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework springAntoine Rey
 
오픈소스로 구축하는 클라우드 이야기
오픈소스로 구축하는 클라우드 이야기오픈소스로 구축하는 클라우드 이야기
오픈소스로 구축하는 클라우드 이야기Nalee Jang
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFCSunil OS
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Anton Arhipov
 
Enterprise Tic-Tac-Toe
Enterprise Tic-Tac-ToeEnterprise Tic-Tac-Toe
Enterprise Tic-Tac-ToeScott Wlaschin
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.pptVarshini62
 
Linux Interview Questions And Answers | Linux Administration Tutorial | Linux...
Linux Interview Questions And Answers | Linux Administration Tutorial | Linux...Linux Interview Questions And Answers | Linux Administration Tutorial | Linux...
Linux Interview Questions And Answers | Linux Administration Tutorial | Linux...Edureka!
 
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...ScyllaDB
 
Debug Information And Where They Come From
Debug Information And Where They Come FromDebug Information And Where They Come From
Debug Information And Where They Come FromMin-Yih Hsu
 
도커 무작정 따라하기: 도커가 처음인 사람도 60분이면 웹 서버를 올릴 수 있습니다!
도커 무작정 따라하기: 도커가 처음인 사람도 60분이면 웹 서버를 올릴 수 있습니다!도커 무작정 따라하기: 도커가 처음인 사람도 60분이면 웹 서버를 올릴 수 있습니다!
도커 무작정 따라하기: 도커가 처음인 사람도 60분이면 웹 서버를 올릴 수 있습니다!pyrasis
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesecosio GmbH
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingKumar
 

Mais procurados (20)

Testing Spring Boot Applications
Testing Spring Boot ApplicationsTesting Spring Boot Applications
Testing Spring Boot Applications
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework spring
 
오픈소스로 구축하는 클라우드 이야기
오픈소스로 구축하는 클라우드 이야기오픈소스로 구축하는 클라우드 이야기
오픈소스로 구축하는 클라우드 이야기
 
C# - Part 1
C# - Part 1C# - Part 1
C# - Part 1
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
 
Unit 7 Java
Unit 7 JavaUnit 7 Java
Unit 7 Java
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Enterprise Tic-Tac-Toe
Enterprise Tic-Tac-ToeEnterprise Tic-Tac-Toe
Enterprise Tic-Tac-Toe
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.ppt
 
Linux Interview Questions And Answers | Linux Administration Tutorial | Linux...
Linux Interview Questions And Answers | Linux Administration Tutorial | Linux...Linux Interview Questions And Answers | Linux Administration Tutorial | Linux...
Linux Interview Questions And Answers | Linux Administration Tutorial | Linux...
 
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
 
Debug Information And Where They Come From
Debug Information And Where They Come FromDebug Information And Where They Come From
Debug Information And Where They Come From
 
도커 무작정 따라하기: 도커가 처음인 사람도 60분이면 웹 서버를 올릴 수 있습니다!
도커 무작정 따라하기: 도커가 처음인 사람도 60분이면 웹 서버를 올릴 수 있습니다!도커 무작정 따라하기: 도커가 처음인 사람도 60분이면 웹 서버를 올릴 수 있습니다!
도커 무작정 따라하기: 도커가 처음인 사람도 60분이면 웹 서버를 올릴 수 있습니다!
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Java
JavaJava
Java
 

Semelhante a CodeIgniter & MVC

Staying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHPStaying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHPOscar Merida
 
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)Roman Zenner
 
cake phptutorial
cake phptutorialcake phptutorial
cake phptutorialice27
 
Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3Drupalcon Paris
 
Get things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplicationsGet things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplicationsGiuliano Iacobelli
 
Lecture 4_Laravel Controller and Data Pass-Route.pptx
Lecture 4_Laravel Controller and Data Pass-Route.pptxLecture 4_Laravel Controller and Data Pass-Route.pptx
Lecture 4_Laravel Controller and Data Pass-Route.pptxSaziaRahman
 
Asp.net c# MVC-5 Training-Day-2 of Day-9
Asp.net c# MVC-5 Training-Day-2 of Day-9Asp.net c# MVC-5 Training-Day-2 of Day-9
Asp.net c# MVC-5 Training-Day-2 of Day-9AHM Pervej Kabir
 
Introduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersIntroduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersAoteaStudios
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindValentine Matsveiko
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...LEDC 2016
 
OroCRM Partner Technical Training: September 2015
OroCRM Partner Technical Training: September 2015OroCRM Partner Technical Training: September 2015
OroCRM Partner Technical Training: September 2015Oro Inc.
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_HourDilip Patel
 
Library management system
Library management systemLibrary management system
Library management systemsiddiqui241993
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code FirstJames Johnson
 
Code igniter - A brief introduction
Code igniter - A brief introductionCode igniter - A brief introduction
Code igniter - A brief introductionCommit University
 

Semelhante a CodeIgniter & MVC (20)

Staying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHPStaying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHP
 
Codeinator
CodeinatorCodeinator
Codeinator
 
Codeigniter
CodeigniterCodeigniter
Codeigniter
 
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)
 
cake phptutorial
cake phptutorialcake phptutorial
cake phptutorial
 
Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3
 
Get things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplicationsGet things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplications
 
Lecture 4_Laravel Controller and Data Pass-Route.pptx
Lecture 4_Laravel Controller and Data Pass-Route.pptxLecture 4_Laravel Controller and Data Pass-Route.pptx
Lecture 4_Laravel Controller and Data Pass-Route.pptx
 
Asp.net c# MVC-5 Training-Day-2 of Day-9
Asp.net c# MVC-5 Training-Day-2 of Day-9Asp.net c# MVC-5 Training-Day-2 of Day-9
Asp.net c# MVC-5 Training-Day-2 of Day-9
 
Introduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersIntroduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developers
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
 
OroCRM Partner Technical Training: September 2015
OroCRM Partner Technical Training: September 2015OroCRM Partner Technical Training: September 2015
OroCRM Partner Technical Training: September 2015
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
Codeigniter
CodeigniterCodeigniter
Codeigniter
 
Library management system
Library management systemLibrary management system
Library management system
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
La sql
La sqlLa sql
La sql
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 
Code igniter - A brief introduction
Code igniter - A brief introductionCode igniter - A brief introduction
Code igniter - A brief introduction
 

Mais de Jamshid Hashimi

Week 2: Getting Your Hands Dirty – Part 2
Week 2: Getting Your Hands Dirty – Part 2Week 2: Getting Your Hands Dirty – Part 2
Week 2: Getting Your Hands Dirty – Part 2Jamshid Hashimi
 
Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1Jamshid Hashimi
 
Introduction to C# - Week 0
Introduction to C# - Week 0Introduction to C# - Week 0
Introduction to C# - Week 0Jamshid Hashimi
 
RIST - Research Institute for Science and Technology
RIST - Research Institute for Science and TechnologyRIST - Research Institute for Science and Technology
RIST - Research Institute for Science and TechnologyJamshid Hashimi
 
How Coding Can Make Your Life Better
How Coding Can Make Your Life BetterHow Coding Can Make Your Life Better
How Coding Can Make Your Life BetterJamshid Hashimi
 
Tips for Writing Better Code
Tips for Writing Better CodeTips for Writing Better Code
Tips for Writing Better CodeJamshid Hashimi
 
Launch Your Local Blog & Social Media Integration
Launch Your Local Blog & Social Media IntegrationLaunch Your Local Blog & Social Media Integration
Launch Your Local Blog & Social Media IntegrationJamshid Hashimi
 
Introduction to Blogging
Introduction to BloggingIntroduction to Blogging
Introduction to BloggingJamshid Hashimi
 
Introduction to Wordpress
Introduction to WordpressIntroduction to Wordpress
Introduction to WordpressJamshid Hashimi
 
CodeIgniter Helper Functions
CodeIgniter Helper FunctionsCodeIgniter Helper Functions
CodeIgniter Helper FunctionsJamshid Hashimi
 
CodeIgniter Class Reference
CodeIgniter Class ReferenceCodeIgniter Class Reference
CodeIgniter Class ReferenceJamshid Hashimi
 
Managing Applications in CodeIgniter
Managing Applications in CodeIgniterManaging Applications in CodeIgniter
Managing Applications in CodeIgniterJamshid Hashimi
 
PHP Frameworks & Introduction to CodeIgniter
PHP Frameworks & Introduction to CodeIgniterPHP Frameworks & Introduction to CodeIgniter
PHP Frameworks & Introduction to CodeIgniterJamshid Hashimi
 

Mais de Jamshid Hashimi (20)

Week 2: Getting Your Hands Dirty – Part 2
Week 2: Getting Your Hands Dirty – Part 2Week 2: Getting Your Hands Dirty – Part 2
Week 2: Getting Your Hands Dirty – Part 2
 
Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1
 
Introduction to C# - Week 0
Introduction to C# - Week 0Introduction to C# - Week 0
Introduction to C# - Week 0
 
RIST - Research Institute for Science and Technology
RIST - Research Institute for Science and TechnologyRIST - Research Institute for Science and Technology
RIST - Research Institute for Science and Technology
 
How Coding Can Make Your Life Better
How Coding Can Make Your Life BetterHow Coding Can Make Your Life Better
How Coding Can Make Your Life Better
 
Mobile Vision
Mobile VisionMobile Vision
Mobile Vision
 
Tips for Writing Better Code
Tips for Writing Better CodeTips for Writing Better Code
Tips for Writing Better Code
 
Launch Your Local Blog & Social Media Integration
Launch Your Local Blog & Social Media IntegrationLaunch Your Local Blog & Social Media Integration
Launch Your Local Blog & Social Media Integration
 
Customizing Your Blog 2
Customizing Your Blog 2Customizing Your Blog 2
Customizing Your Blog 2
 
Customizing Your Blog 1
Customizing Your Blog 1Customizing Your Blog 1
Customizing Your Blog 1
 
Introduction to Blogging
Introduction to BloggingIntroduction to Blogging
Introduction to Blogging
 
Introduction to Wordpress
Introduction to WordpressIntroduction to Wordpress
Introduction to Wordpress
 
CodeIgniter Helper Functions
CodeIgniter Helper FunctionsCodeIgniter Helper Functions
CodeIgniter Helper Functions
 
CodeIgniter Class Reference
CodeIgniter Class ReferenceCodeIgniter Class Reference
CodeIgniter Class Reference
 
Managing Applications in CodeIgniter
Managing Applications in CodeIgniterManaging Applications in CodeIgniter
Managing Applications in CodeIgniter
 
CodeIgniter Practice
CodeIgniter PracticeCodeIgniter Practice
CodeIgniter Practice
 
PHP Frameworks & Introduction to CodeIgniter
PHP Frameworks & Introduction to CodeIgniterPHP Frameworks & Introduction to CodeIgniter
PHP Frameworks & Introduction to CodeIgniter
 
Exception & Database
Exception & DatabaseException & Database
Exception & Database
 
MySQL Record Operations
MySQL Record OperationsMySQL Record Operations
MySQL Record Operations
 
MySQL JOIN & UNION
MySQL JOIN & UNIONMySQL JOIN & UNION
MySQL JOIN & UNION
 

Último

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 

Último (20)

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

CodeIgniter & MVC

  • 1. CodeIgniter & MVC Jamshid Hashimi Trainer, Cresco Solution http://www.jamshidhashimi.com jamshid@netlinks.af @jamshidhashimi ajamshidhashimi Afghanistan Workforce Development Program
  • 2. Agenda • Supported Features • Understanding MVC • Application Flow Chart • CodeIgniter URLS • CodeIgniter Controllers • Views • Models • Helpers • Libraries • Hooks
  • 3. Supported Feaures • Model-View-Controller Based System • Extremely Light Weight • Full Featured database classes with support for several platforms. • Active Record Database Support • Form and Data Validation • Security and XSS Filtering • Session Management • Email Sending Class. Supports Attachments, HTML/Text email, multiple protocols (sendmail, SMTP, and Mail) and more. • Image Manipulation Library (cropping, resizing, rotating, etc.). Supports GD, ImageMagick, and NetPBM
  • 4. Supported Feaures • File Uploading Class • FTP Class • Localization • Pagination • Data Encryption • Benchmarking • Full Page Caching • Error Logging • Application Profiling • Calendaring Class • User Agent Class
  • 5. Supported Feaures • Zip Encoding Class • Template Engine Class • Trackback Class • XML-RPC Library • Unit Testing Class • Search-engine Friendly URLs • Flexible URI Routing • Support for Hooks and Class Extensions • Large library of "helper" functions
  • 6. Understanding MVC • CodeIgniter is based on the Model-View- Controller development pattern. MVC is a software approach that separates application logic from presentation. – The Model represents your data structures. – The View is the information that is being presented to a user. – The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page.
  • 8. CodeIgniter URLS • By default, URLs in CodeIgniter are designed to be search-engine and human friendly. • CodeIgniter uses a segment-based approach. example.com/news/article/my_article
  • 9. CodeIgniter URLS • The first segment represents the controller class that should be invoked. • The second segment represents the class function, or method, that should be called. • The third, and any additional segments, represent the ID and any variables that will be passed to the controller. example.com/class/function/ID
  • 10. CodeIgniter URLS • Removing index.php RewriteEngine on RewriteCond $1 !^(index.php|images|robots.txt) RewriteRule ^(.*)$ /index.php/$1 [L]
  • 11. DEMO
  • 12. CodeIgniter Controllers • A Controller is simply a class file that is named in a way that can be associated with a URI. • When a controller's name matches the first segment of a URI, it will be loaded. <?php class Blog extends CI_Controller { public function index() { echo 'Hello World!'; } } ?>
  • 13. CodeIgniter Controllers • The second segment of the URI determines which function in the controller gets called. <?php class Blog extends CI_Controller { public function index() { echo 'Hello World!'; } public function comments() { echo 'Look at this!'; } } ?>
  • 14. CodeIgniter Controllers • If your URI contains more then two segments they will be passed to your function as parameters. <?php class Products extends CI_Controller { public function shoes($sandals, $id) { echo $sandals; echo $id; } } ?>
  • 15. CodeIgniter Controllers • Constructors are useful if you need to set some default values, or run a default process when your class is instantiated. Constructors can't return a value, but they can do some default work. <?php class Blog extends CI_Controller { public function __construct() { parent::__construct(); // Your own constructor code } } ?>
  • 16. DEMO
  • 17. Views • A view is simply a web page, or a page fragment, like a header, footer, sidebar, etc. In fact, views can flexibly be embedded within other views (within other views, etc., etc.) if you need this type of hierarchy. $this->load->view('view.php');
  • 18. Views • CodeIgniter will intelligently handle multiple calls to $this->load->view from within a controller. <?php class Page extends CI_Controller { function index() { $data['page_title'] = 'Your title'; $this->load->view('header'); $this->load->view('menu'); $this->load->view('content', $data); $this->load->view('footer'); } } ?>
  • 19. Views • Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading function. $data = array( 'title' => 'My Title', 'heading' => 'My Heading', 'message' => 'My Message' ); $this->load->view('blogview', $data);
  • 20. Views • The data array you pass to your view files is not limited to simple variables. You can pass multi dimensional arrays, which can be looped to generate multiple rows. <?php class Blog extends CI_Controller { function index() { $data['todo_list'] = array('Clean House', 'Call Mom', 'Run Errands'); $data['title'] = "My Real Title"; $data['heading'] = "My Real Heading"; $this->load->view('blogview', $data); } } ?>
  • 21. Views <html> <head> <title><?php echo $title;?></title> </head> <body> <h1><?php echo $heading;?></h1> <h3>My Todo List</h3> <ul> <?php foreach ($todo_list as $item):?> <li><?php echo $item;?></li> <?php endforeach;?> </ul> </body> </html>
  • 22. DEMO
  • 23. Models • Models are PHP classes that are designed to work with information in your database. class Model_name extends CI_Model { function __construct() { parent::__construct(); } }
  • 24. Models $this->load->model('Model_name'); $config['hostname'] = "localhost"; $config['username'] = "myusername"; $config['password'] = "mypassword"; $config['database'] = "mydatabase"; $config['dbdriver'] = "mysql"; $config['dbprefix'] = ""; $config['pconnect'] = FALSE; $config['db_debug'] = TRUE;
  • 25. DEMO
  • 26. Helpers • Helpers, as the name suggests, help you with tasks. Each helper file is simply a collection of functions in a particular category. • Unlike most other systems in CodeIgniter, Helpers are not written in an Object Oriented format. They are simple, procedural functions. Each helper function performs one specific task, with no dependence on other functions.
  • 28. Helpers • Extending Helpers – To "extend" Helpers, create a file in your application/helpers/ folder with an identical name to the existing Helper, but prefixed with MY_ – The term "extend" is used loosely since Helper functions are procedural and discrete and cannot be extended in the traditional programmatic sense.
  • 29. DEMO
  • 30. Libraries • All of the available libraries are located in your system/libraries folder. $this->load->library('class name'); $this->load->library(array('email', 'table'));
  • 31. Libraries • CodeIgniter permits your libraries to extend native classes if you simply need to add some functionality to an existing library. Or you can even replace native libraries just by placing identically named versions in your application/libraries folder. – You can create entirely new libraries. – You can extend native libraries. – You can replace native libraries.
  • 32. Libraries • File names must be capitalized. For example: Myclass.php • Class declarations must be capitalized. For example: class Myclass • Class names and file names must match.
  • 33. Libraries <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Someclass { public function some_function() { } } /* End of file Someclass.php */ $this->load->library('someclass'); $this->someclass->some_function();
  • 34. Libraries • You can use class constructor for initializing data <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Someclass { public function __construct($params) { // Do something with $params } } ?>
  • 35. Libraries • Utilizing CodeIgniter Resources $CI =& get_instance(); $CI->load->helper('url'); $CI->load->library('session'); $CI->config->item('base_url'); etc.
  • 36. Libraries • Replacing Native Libraries with Your Versions – To use this feature you must name the file and the class declaration exactly the same as the native library. – Note that most native classes are prefixed with CI_. class CI_Email { }
  • 37. Libraries • If all you need to do is add some functionality to an existing library - perhaps add a function or two - then it's overkill to replace the entire library with your version. In this case it's better to simply extend the class. Extending a class is nearly identical to replacing a class with a couple exceptions: – The class declaration must extend the parent class. – Your new class name and filename must be prefixed with MY_
  • 38. Libraries • The parent constructor must be called, whenever we want to have to use a constructor in our own library. class MY_Email extends CI_Email { public function __construct() { parent::__construct(); } }
  • 39. Libraries • Setting your own prefix – To set your own sub-class prefix, open your application/config/config.php file and look for this item: $config['subclass_prefix'] = 'MY_';
  • 40. DEMO
  • 41. Hooks • CodeIgniter's Hooks feature provides a means to tap into and modify the inner workings of the framework without hacking the core files. – For example, you might want to run a script right before your controllers get loaded, or right after, or you might want to trigger one of your own scripts in some other location. $config['enable_hooks'] = TRUE;
  • 42. Hooks • Hooks are defined in application/config/hooks.php file. Each hook is specified as an array with this prototype: $hook['pre_controller'] = array( 'class' => 'MyClass', 'function' => 'Myfunction', 'filename' => 'Myclass.php', 'filepath' => 'hooks', 'params' => array('milk', 'tea', 'fruit') );
  • 43. Hooks • class The name of the class you wish to invoke. If you prefer to use a procedural function instead of a class, leave this item blank. • function The function name you wish to call. • filename The file name containing your class/function. • filepath The name of the directory containing your script. Note: Your script must be located in a directory INSIDE your application folder, so the file path is relative to that folder. For example, if your script is located in application/hooks, you will simply use hooks as your filepath. If your script is located in application/hooks/utilities you will use hooks/utilities as your filepath. No trailing slash. • params Any parameters you wish to pass to your script. This item is optional.
  • 44. Hooks • Hook Points – pre_system: Called very early during system execution. Only the benchmark and hooks class have been loaded at this point. No routing or other processes have happened. – pre_controller: Called immediately prior to any of your controllers being called. All base classes, routing, and security checks have been done. – post_controller_constructor: Called immediately after your controller is instantiated, but prior to any method calls happening. – post_controller: Called immediately after your controller is fully executed.
  • 45. Hooks – display_override: Overrides the _display() function, used to send the finalized page to the web browser at the end of system execution. This permits you to use your own display methodology. Note that you will need to reference the CI superobject with $this->CI =& get_instance() and then the finalized data will be available by calling $this->CI- >output->get_output() – cache_override: Enables you to call your own function instead of the _display_cache() function in the output class. This permits you to use your own cache display mechanism. – post_system: Called after the final rendered page is sent to the browser, at the end of system execution after the finalized data is sent to the browser.
  • 46. DEMO

Notas do Editor

  1. URI: Uniform resource identifier