0% found this document useful (0 votes)
97 views

Codeigniter and MVC: Enterprise Class Web Application Development

The document discusses CodeIgniter, an open source PHP-based Model-View-Controller (MVC) web application framework. It begins by explaining the motivation for using frameworks like CodeIgniter, namely to add structure and separation of concerns to growing websites. It then provides an overview of the MVC pattern and CodeIgniter's features, which include being lightweight, fast, extensible and having clean URLs. Key aspects of CodeIgniter like routing, directories and application flow are also summarized.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views

Codeigniter and MVC: Enterprise Class Web Application Development

The document discusses CodeIgniter, an open source PHP-based Model-View-Controller (MVC) web application framework. It begins by explaining the motivation for using frameworks like CodeIgniter, namely to add structure and separation of concerns to growing websites. It then provides an overview of the MVC pattern and CodeIgniter's features, which include being lightweight, fast, extensible and having clean URLs. Key aspects of CodeIgniter like routing, directories and application flow are also summarized.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

CodeIgniter and MVC

Enterprise class web application development

Dienstag, 4. Mai 2010


Motivation

• You have worked with PHP, for small sites this works very well. HTML files
can be easily extended with dynamic content from the database, form
processing, etc.

• When sites grow, you might have realized that across multiple pages lots of
code repetition occurs. This is a problem when you need to change certain
parts of a page, that affects many or all pages.

• Furthermore, its hard to introduce new developers to code someone else


has written. It takes a long time to get familar with the code.

Dienstag, 4. Mai 2010


Motivation

• Enterprise class (big) web applications need structure, one HTML file per
page with PHP code is not optimal => things get confusing, hard to work in
teams, etc.

• Web Application Frameworks provide such a structure wich introduce


seperation of concern, etc.

• Most common for Web application development are frameworks that are
based on the Model-View-Controller design pattern

Dienstag, 4. Mai 2010


Model-View-Controller

• „Seperation of concerns“ of Logic and Presentation

• Controller: Handles all incoming HTTP requests, passes data to the views

• View: Renders the HTML output

• Models: Encapsulate Business Logic, such as interaction with the database

• For PHP we introduce CodeIgniter

Dienstag, 4. Mai 2010


CodeIgniter

• CodeIgniter is a PHP-based MVC framework that helps structure your code


and make redundant tasks less tedious.

• There are countless similar PHP frameworks, the most popular ones being
CakePHP and symfony. Ruby on Rails is famous in the Ruby world.

• CodeIgniter is very light weight. It doesn‘t force any convention but provides
many commonly required features through a set of build in libraries.

• CodeIgniter has a low learning curve and is one of the best documented PHP
web frameworks.

Dienstag, 4. Mai 2010


CodeIgniter is right for you if:
• You want a framework with a small footprint.
• You need exceptional performance.
• You need broad compatibility with standard hosting accounts that run a
variety of PHP versions and configurations.
• You want a framework that requires nearly zero configuration.
• You want a framework that does not require you to use the command
line.
• You want a framework that does not require you to adhere to restrictive
coding rules.
• You are not interested in large-scale monolithic libraries like PEAR.
• You do not want to be forced to learn a templating language (although a
template parser is optionally available if you desire one).
• You eschew complexity, favoring simple solutions.
• You need clear, thorough documentation.
CodeIgniter: Features

• CodeIgniter is Free
CodeIgniter is licensed under the MIT license so you can use it
however you please.

• CodeIgniter is Light Weight


Truly light weight. The core system requires only a few very small
libraries. This is in stark contrast to many frameworks that
require significantly more resources. Additional libraries are
loaded dynamically upon request, based on your needs for a
given process, so the base system is very lean and quite fast.

Dienstag, 4. Mai 2010


CodeIgniter: Features

• CodeIgniter is Fast
Really fast.

• CodeIgniter Uses M-V-C


CodeIgniter uses the Model-View-Controller approach, which
allows great separation between logic and presentation. This is
particularly good for projects in which designers are working
with your template files, as the code these files contain will be
minimized.

• CodeIgniter is Extensible
The system can be easily extended through the use of your own l
ibraries, helpers, or through class extensions or system hooks.
Dienstag, 4. Mai 2010
CodeIgniter: Features

• CodeIgniter Generates Clean URLs


The URLs generated by CodeIgniter are clean and search-engine
friendly. Rather than using the standard “query string” approach to
URLs that is synonymous with dynamic systems, CodeIgniter uses a
segment-based approach:
example.com/news/article/345

• CodeIgniter Packs a Punch


CodeIgniter comes with full-range of libraries that enable the most
commonly needed web development tasks, like accessing a
database, sending email, validating form data, maintaining sessions,
manipulating images, working with XML-RPC data and much more.

Dienstag, 4. Mai 2010


CodeIgniter: Features List

• Extremely Light Weight


• Full Featured database classes with support for several platforms.
• Query Builder 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
• File Uploading Class
• FTP Class
• Localization
• Pagination
Dienstag, 4. Mai 2010
CodeIgniter: Features List

• Data Encryption
• Benchmarking
• Full Page Caching
• Error Logging
• Application Profiling
• Calendaring Class
• User Agent Class
• 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
Dienstag, 4. Mai 2010
Application Flow Chart

1. The index.php serves as the front controller, initializing the base resources needed
to run CodeIgniter.
2. The Router examines the HTTP request to determine what should be done with it.
3. If a cache file exists, it is sent directly to the browser, bypassing the normal
system execution.
4. Security. Before the application controller is loaded, the HTTP request and any
user submitted data is filtered for security.
5. The Controller loads the model, core libraries, plugins, helpers, and any other
resources needed to process the specific request.
6. The finalized View is rendered then sent to the web browser to be seen. If caching
is enabled, the view is cached first so that on subsequent requests it can be
served.
Dienstag, 4. Mai 2010
Installing CodeIgniter
1) Download CodeIgniter from its official website.
https://www.codeigniter.com
2) Unzip CodeIgniter package.
• Downloaded CodeIgniter will be in zip format.
• Unzip it
• Create folder named CodeIgniter in
C>xampp>htdocs
• Copy content of unzip folder inside CodeIgniter
folder.
Installing CodeIgniter
Installing CodeIgniter
• Open browser and type:
localhost/CodeIgniter
Routing Requests

• Per default CodeIgniter maps URL to


controller actions:

/index.php/controller/action

• The default controller is "welcome“


and the default action is "index“.

• Custom routing can be configured


through:

/application/config/routes.php

Dienstag, 4. Mai 2010


Installing CodeIgniter
• Set the base URL in application/config/config.php
file with any text editor
Ex. $config['base_url'] = 'http:localhost/CodeIgniter';
Directory Structure
• CodeIgniter directory structure is
divided into 3 folders:
– Application
– System
– User_guide
And one imp file
– Index.php
Directory Structure : Application
Application - this is where your application code is located, including
the model, view and controller classes. This is the folder where you
will develop your project. The Application folder contains several
other folders, which are explained below:
• Cache: This folder contains all the cached pages of your
application. These cached pages will increase the overall speed of
accessing the pages.
• Config: This folder contains various files to configure the
application. With the help of config.php file, user can configure the
application. Using database.php ile, user can configure the database
of the application.
• Controllers: This folder holds the controllers of your application.
Directory Structure : Application
• Core: CodeIgniter has some core class, these class make up the
CodeIgniter framework and are saved in core file.
• Generally, there will be no need to change these classes, but in
case if you are modifying a class, create a class in
"application/core" folder having same name as the core class
file name in "system" folder.
• Helpers: In this folder, you can put own helper class of your
application.
• Hooks: The files in this folder provide a means to tap into and
modify the inner workings of the framework without hacking the
core files.
• Language: This folder contains language related files.
• Libraries: store libraries developed by you for your application.
Directory Structure : Application
• Logs: contains files related to the log of the system. If your
CodeIgniter application is displaying some error or exception
handling messages and if you are not getting what they are, you
can look for their explanation in this folder.
• Models: Models are used to load database queries. Controllers
request model to load database query, model respond it back
and then controller use it.
• Third_party: In this folder, you can place any plugins, which will
be used for your application.
• Views: It contains all your view files. Controller load file from
view and then gives the output.
Directory Structure : System
System
• All action of CodeIgniter application happens here. Contains all
CodeIgniter classes and libraries provided by the framework.
• Core - It contains CodeIgniter core class. Do not make any
changes in this folder.
• Database - It contains database drivers and other utilities.
• Fonts - It contains font related information.
• Helpers - It contains default helpers such as URL, date and cookie.
• Language - CodeIgniter supports multilingual web applications. It
contains default language file.
• Libraries - It contain libraries like calendars, file upload, email,
etc. libraries created by you will be saved in
"application/libraries". Here, only standard libraries will be
Directory Structure
User_guide

It is the offline CodeIgniter guide.Core - It contains CodeIgniter core


class. Do not make any changes in this folder.

Index.php
• In this file, we can set the application environment and error level
and we can define system and application folder name.
• recieves all requests and routes to the right controllers classes
and actions, parameters are included in the URL
MVC
• Models are objects, which represent the
underlying data. They hover above the database
and access it as required. They can also perform
operations on data to add meaning to it.
• Views show the state of the model. They are
responsible for displaying information to the end
user.
• Controllers offer options to change the state of
the model. They are responsible for consulting
models. They provide the dynamic data to views.
MVC
• CI has subfolders for models, views, and controllers.
Each file within them is a .php file, usually in the form
of a class that follows certain naming conventions.
• CI MVC is based on
• Loose Coupling: Coupling is the degree to which the
components of a system rely on each other. The less
the components depend on each other, the more re-
usable and flexible the system becomes.
• Component Singularity: Singularity is the degree to
which components have a narrowly focused purpose.
In CodeIgniter, each class and its functions are highly
autonomous in order to allow maximum usefulness.
Controller
• A controller is the intermediary between models and views to
process HTTP request and generates a web page.
• Must extend the main Controller class of CodeIgniter
(CI_Controller)
• Each class function represents an controller action, which is
redering a HTML page
• index() is the default action
• The name of the controller class must start with an uppercase
letter.
• The controller must be called with lowercase letter.
• Default Controller: The file specified in default controller will be
loaded by default when no file name is mentioned in the URL. By
default, it is Welcome.php which is the first page to be seen after
installing CodeIgniter.
Controller
• Default Controller
• To specify own default controller, open
your application/config/routes.php file and
set this variable:
$route['default_controller'] = ‘Test';
• Where ‘Test’ is the name of the controller
class you want used
Controller Example
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Test extends CI_Controller // controller class


{
public function index() //default method of controller
{
$this->load->view('hello_world'); //load view (hello_world.jsp)
echo ‘I am inside controller test’s index Method';
}
}
?>

• save this file as test.php in C:\xampp\htdocs\CodeIgniter\application\controllers


• Now visit the your site using a URL similar to this:
localhost/CodeIgniter/index.php/Test
Controller: Creating own Method
• Since your controller classes will extend the
main application controller you must be
careful not to name your functions identically
to the ones used by that class, otherwise your
local functions will override them.
Controller: Method Example
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Test extends CI_Controller // controller class


{
public function myfunction() //default method of controller
{
$this->load->view('hello_world'); //load view (hello_world.jsp)
echo ‘I am inside controller test’s my function Method';
}
}
?>

• save this file as test.php in


C:\xampp\htdocs\CodeIgniter\application\controllers
• Now visit the your site using a URL similar to this:
localhost/CodeIgniter/index.php/Test/myfunction
Controller: Loading Multiple Views
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class MyHello extends CI_Controller {

public function hi()


{
$this->load->view('hello_function');
$this->load->view('hello_world');
$this->load->view('hello_framework');
}
}
?>
Remapping Function Calls

• The second segment of the URI typically determines


which function in the controller gets called.
CodeIgniter permits you to override this behavior
through the use of the _remap() function

• If your controller contains a function named _remap(),


it will always get called regardless of what your URI
contains. It overrides the normal behavior in which
the URI determines which function is called, allowing
you to define your own function routing rules.
Remapping Function Calls
<?php function _remap($method)
defined('BASEPATH') OR exit('No {
direct script access allowed');
// $method contains the function
//name from URI ,that is second
class Hello extends CI_Controller { //segment.
switch($method)
public function defacult_function() { {
$this->load->view(‘Error_Page');} case 'function':
$this->myfunction();
public function myfunction() { break;
$this->load->view('hello_function'); } case 'framework':
$this->framefunction();
public function framefunction() { break;
$this->load>view('hello_framework'); default:
} $this->defacult_function();
break; } } }
?>
Class Constructors
• If you intend to use a constructor in any of your
Controllers, you MUST place the following line of
code in it:
parent::__construct();
• The reason this line is necessary is because your
local constructor will be overriding the one in
the parent controller class so we need to
manually call it.
Class Constructors
<?php
class Blog extends CI_Controller {

public function __construct()


{
parent::__construct();
// Your own constructor code
}
}
?>
VIEW
• 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.
Creating a View
• Using your text editor, create a file
called hello_world.php, and put this in it:
<html>
<head>
<title>My Blog</title>
</head>
<body>
<h1>Welcome to my Blog!</h1>
</body>
</html>
Then save the file in application/views/ folder.
Loading View
• To load a particular view file you will use the
following function:
• $this->load->view('name');
• Where name is the name of your view file. Note:
The .php file extension does not need to be
specified unless you use something other
than .php.
• Ex: $this->load->view('hello_world');
• Above code need to be included in function of
controller
Loading multiple views
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');

class MyHello extends CI_Controller {


public function hi()
{
$this->load->view('hello_function');
$this->load->view('hello_world');
$this->load->view('hello_framework');
}
} ?>
Storing Views within Sub-folders

• Your view files can also be stored within sub-


folders if you prefer that type of organization.
When doing so you will need to include the
folder name loading the view.
• Example:

$this->load->view('folder_name/file_name');
Adding Dynamic Data to the View
• 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
• If you use an object, the class variables will
be turned into array elements.
Adding Dynamic Data to the View:Array
Controller: ViewArray.php View: firsthome.php
<?php <html>
class ViewArray extends CI_Controller <head>
{ <title><?php echo $title;?></title>
function index()
{ </head>
$data=array( <body>
'title'=>'Homepage', <h1><?php echo $content;?></h1>
'content'=>'Welcome Here‘ </body>
); </html>
$this->load->view('firsthome',$data);
}
}
?>
Adding Dynamic Data to the View:Object
Controller: ViewObj.php View: sechome.php
<?php <html>
class ViewObj extends CI_Controller <head>
{ <title><?php echo $title;?></title>
function index() </head>
{ <body>
$data['title'] = "Homepage"; <h1><?php echo $content;?></h1>
$data['content'] ="Frameworks !!"; </body>
</html>
$this->load->view('sechome', $data);
}
}
?>
Creating Loops
(Controller: Comp.php)
<?php
class Comp extends CI_Controller
{
function index()
{
$data=array(
'title'=>'Company Homepage',
'content'=>'Welcome to kJSCE',
'projects'=>array('library management
system','online shopping system','provident fund statutory returns
system','hotel management system')
);
$this->load->view('home',$data, false);
}
}
?>
Creating Loops
(View: home.php)
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<br>
<h1><?php echo $content;?></h1>
<br><hr>
<h2>Projects done:<h2>
<ul>
<?php foreach($projects as $item){?>
<li><?php echo $item;?></li>
<?php }?>
</ul>
</body>
</html>
Model
• In any application you need to call a function to
retrieve some information from the database.
• Models responsibility is to handle all data logic
and representation and load data in the views.
• Model classes are stored in
your application/models/ folder.
• They can be nested within sub-folders if you
want this type of organization.
Model
Basic Prototype Example
class Model_name extends CI_Model { class User_model extends CI_Model {

function __construct() function __construct()


{ {
parent::__construct(); parent::__construct();
} }
} }

• Where Model_name is the name of your class.


• Class names must have the first letter capitalized with the rest
of the name lowercase.
• Make sure your class extends the base Model class.
• The file name will be a lower case version of your class name.
Loading Model
• Your models will typically be loaded and called from within
your controller functions.
• To load a model you will use the following function:
$this->load->model('Model_name');
• If your model is located in a sub-folder, include the relative
path from your models folder.
• For example, if you have a model located
at application/models/blog/queries.php you'll load it
using:
$this->load->model('blog/queries');
• Once loaded, you will access your model functions using
an object with the same name as your class:
$this->Model_name->function();
Loading Model
• If you would like your model assigned to a
different object name you can specify it via
the second parameter of the loading function:
EX:
$this->load->model('Model_name', 'fubar');
$this->fubar->function();
Connecting Models to Database
• Loading a model doesn't mean it will
automatically connect to your database. There
are different methods to connect a database.
• .Auto-connect feature will automatically load
your database with every page load. To enable it,
add word 'database' in the array library in
autoload.php file.
• Manually connect database by adding this code
in the page where needed.
$this->load->database();
Helper
• Helpers help you with tasks.
• Each helper file is simply a collection of functions
in a particular category.
• There are
– URL Helpers, that assist in creating links,
– Form Helpers that help you create form elements,
– Text Helpers perform various text formatting routines
– Cookie Helpers set and read cookies,
– File Helpers help you deal with files, etc
Helper
• Helpers are simple, procedural functions.
• Each helper function performs one specific task, with no
dependence on other functions.
• CodeIgniter does not load Helper Files by default, so the first
step in using a Helper is to load it.
• Once loaded, it becomes globally available in
your controller and views.
• Helpers are typically stored in your system/helpers,
or application/helpers directory.
• CodeIgniter will look first in your application/helpers directory.
If the directory does not exist or the specified helper is not
located there CI will instead look in your
global system/helpers folder.
Helper
• To load multiple helpers, specify them in an array,
$this->load->helper( array('helper1', 'helper2', 'helper3') );
HTML Helper: heading()
• Heading() returns HTML heading tag
• Parameters:
– $data (string) – Content
– $h (string) – Heading level
– $attributes (mixed) – HTML attributes
• Lets you create HTML heading tags. The first parameter will
contain the data, the second the size of the heading.
Example:
• echo heading('Welcome!', 3);
• The above would produce: <h3>Welcome!</h3>
HTML Helper: heading()
• Additionally, in order to add attributes to the heading tag
such as HTML classes, ids or inline styles, a third parameter
accepts either a string or an array:
• echo heading('Welcome!', 3, 'class="pink"');
• echo heading('How are you?', 4, array('id' => 'question',
'class' => 'green'));
• The above code produces:
• <h3 class="pink">Welcome!<h3> <h4 id="question"
class="green">How are you?</h4>
HTML Helper: br()
• br() Returns HTML line break tag
• Parameters:
– $count (int) – Number of times to repeat the tag
• Generates line break tags (<br />) based on the number you
submit.
• Example: echo br(3);
• The above would produce:
<br /><br /><br />
HTML Helper: ul()
• ul() Returns: HTML-formatted unordered list
• Parameters:
– $list (array) – List entries
– $attributes (array) – HTML attributes

• Permits you to generate unordered HTML lists from


simple or multi-dimensional arrays.
• Example:
• $list = array( 'red', 'blue', 'green', 'yellow' );
$attributes = array( 'class' => 'boldlist', 'id' =>
'mylist' );
echo ul($list, $attributes);
HTML Helper: ol()
• ol() Returns: HTML-formatted ordered list
• Parameters:
– $list (array) – List entries
– $attributes (array) – HTML attributes

• Permits you to generate ordered HTML lists from


simple or multi-dimensional arrays.
• Example:
• $list = array( 'red', 'blue', 'green', 'yellow' );
$attributes = array( 'class' => 'boldlist', 'id' =>
'mylist' );
echo ol($list, $attributes);
Active Records

• CodeIgniter uses a modified version of Selecting Data


the Active Record Database Pattern.

• This pattern allows information to be


retrieved, inserted, and updated in
your database with minimal scripting.

Inserting Data

Method Chaining

Dienstag, 4. Mai 2010


CI Database
Database Configuration
Initializing the Database Class
• The following code loads and initializes the database
class based on your configuration settings:
$this->load->database();
• Once loaded the class is ready to be used
Database Configuration

• CodeIgniter has a config file that lets you


store your database connection values
(username, password, database name, etc.).
The config file is located at
application/config/database.php
• The config
settings are
stored in a
multi-
dimensional
array with this
prototype
Connecting to your Database
There are two ways to connect to a database:
• Automatically Connecting
• Manually Connecting
• Automatically Connecting
• The “auto connect” feature will load and
instantiate the database class with every page
load. To enable “auto connecting”, add the
word database to the library array, as
indicated in the following file:
application/config/autoload.php
• Manually Connecting
• If only some of your pages require database
connectivity you can manually connect to
your database by adding this line of code in
any function where it is needed, or in your
class constructor to make the database
available globally in that class.
• $this->load->database();
• If helpers are used then one need to
configure the following file:
application/config/autoload.php
Ex:
$autoload[‘helper’]=array(‘html’, ‘form’, ‘url’)

You might also like