Notes on CodeIgniter - The Risberg Family

arrogantpreviousInternet και Εφαρμογές Web

2 Φεβ 2013 (πριν από 4 χρόνια και 9 μήνες)

200 εμφανίσεις

Page
1

of
21

Notes on
CodeIgnit
e
r

Created

02/27/
09

Updated 11/30/11
, Updated 12/04/11
, Updated 03/25/
12
, U
pdated 03/28/12, U
pdated 04/13
/12
, Updated 05/10/12

Updated 05/31/12
, Updated 06/14/12
, Updated 06/25
/12
, Updated 07/11
/12
, Updated 07/20/12
, Updated 08/0
1/12

Upda
ted 09/12/12
, Updated 09/22
/12
, Updated 10/05/12
, Updated 10/22
/12
, Updated 11/25
/12
, Updated 12/02
/12

Introduction

CodeIgniter is a
PHP framework

developed by EllisLab, and used
as the basis for

their ExpressionEngine product.

It
provides an MVC paradigm

for your PHP applications, with a much smaller footprint than frameworks such as Zend.

The
use of MVC is similar to that in Ruby on Rails, and in fact many of the conventions in CodeIgniter are based on those in
Rails.


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 force
d 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


Currently on version 2.1.
3
, released in
early fall

2012.

The
re are plans for the next release to be called 3.0, even though it
is a smaller change than is typical for a

3.0


number, as the licensing terms are going to be changed.

Resources

“CodeIgniter Handbook


vol 2” by Jamie Rumbelow. September 2012, about 90

pages. Priced at 12 pounds. Self
-
published by efendi books, available at
https://efendibooks.com/books/codeigniter
-
handbook/vol
-
2
.
Contains more
information on REST API’s
.



“CodeI
gniter Handbook


vol

1” by Jamie Rumbelow.
Early 2012,

about

90 pages. Priced at 12 pounds.
Self
-
published
by efendi books, available at
https://efendibooks.com/books/codeigniter
-
handbook/vol
-
1
. One of the few current books on
CI 2.x, this focuses on design of applications, including models, views, controllers, but also REST API’s.



CodeIgniter 1.7 Professional Development
” b
y

Adam Griffiths
.
Packt Publishing
, April 2010, 300 p
ages. Rated 4 stars
on Amazon.com. Available at City of Palo Alto Library.


See
http://net.tutsplus.com/articles/web
-
roundups/30
-
awesome
-
codeigniter
-
tutorials
-
for
-
all
-
skill
-
levels/

Concepts

An application consists of model, controller, and view classes,
along with utilities. The application includes the
CodeIgniter libraries, which are in a package called “system” (this structuring is present in version 2.x, earlier versions
were different
)
.


The flow is shown in the diagram below:

Page
2

of
21



A developer is enco
uraged to think in terms of the MVC elements, and this creates a discipline that might be missing in
other PHP efforts. Class hierarchies are used extensively. Controllers pass information to views using a map, just as how
Grails controllers pass informa
tion to views.


After MVC, the most important feature is the persistence support, done through an Active Object model.


Earlier versions of
CodeIgniter

supported scaffolding, but this was found to be non
-
useful, and was deleted as of release
1.8.


Next, th
e framework supports
configuration

and initialization.


Finally, there are utility classes for features often needed

in social web
applications
, such as
handling sessions,
sending
email, handling file uploads, etc.

Some of these utility classes are packag
ed into “libraries”, and “helpers”. Several of the
classes listed in the CI User’s Guide are actually in libraries that are shipped with the framework, and they must be

configured in


for use.

Installation

Used

the
Softac
ul
ous plugin

on ANHosting
. This
gave us
an installation of version
2.1.0. Created data
base igni495
.
The
app is at /igniter

Defining Models

This appears to be t
he most critical portion of the application, as the models define the persistent objects

and extend from
CI_Model
.
In addition
, the model classes

must define all of the persistence operations, such as get, update, create, and
delete.

The model mu
st make all assignments of field values
.

The model must also implement any filtered retrieve
operations.


This is a large technical de
mand, and in practice we have noticed that many projects implement rather incomplete models,
perhaps skipping aspects of update, create, or delete. Since CI doesn’t have a generator facility at this point (though ther
e
are supporting packages which provid
e some), the allowable variations in models is quite large. In this document we have
tried to standardize these definitions, and provide pointers to sources which are advocating standard and complete model
classes.

Creating Controllers

These extend from C
I_Controller, and are located in the controllers area. Controllers are special in that they can be
referenced by web request actions, specified in the routes.php configuration file.

Creating Views

There is no standard structure for a view, since it is jus
t a PHP file that is composed of HTML with PHP fragments,
however, there are standards for the
location of views in the directory structure, and the organizing of all views for a given
controller into a directory that is named for the controller.

Page
3

of
21


Out of t
he box, CI doesn’t have a facility
for a master layout like in Ruby on Rails or Grails. However, in this document
we discuss how to implement such in your project.

Naming Conventions

All files should have lower
-
case filenames. Use “_” instead of intercap
s. This is because of the
crippled
spl_autoload()

implementation
.


Tables
: plural for primary entities, but join tables are singular at both ends.

Controllers:

companies_controller.php (plural file plus ‘Controller’)

Models:

company_model.php (singular

file name, but plural for the name of table it corresponds to)

Views:

companies/method_name.php (all views for the controller go into a folder whose name matches the controller
name)


We always make my database table names plural and have a one
-
to
-
one re
lationship between my models and tables.
Controllers usually have a corresponding table and model, but not always. Some developers suggest using a
base model

which removes a lot of the tediu
m of setting up a new model for every table which fits into this setup very well and is
probably a big reason that we stick pretty strictly to it.

Model Classes and
Query Builder

Structure of a Model

http://heybigname.com/2009/08/28/how
-
to
-
write
-
a
-
better
-
model
-
in
-
code
-
igniter/


You write a model class for each database table that is to be directly used in query and update operations through the
QueryBuilder

librar
y

(which was formerly called ActiveRecord). It

is also possible to skip active record and write database
calls directly, but we are not enc
ouraging or covering that here.


All model classes extend from CI_Model.
The CI_Model class provide
s access the dat
abase through the $this
-
>db instance
variable. It may also provide some error handling on database exceptions.


Within your model classes, you will typically implement get(), save(), and update() methods, as well as specialized get or
query calls that car
ry out retrieval operations needed by business logic.


There are several methods which can be called on $this
-
>db, such as:


$db
-
>query
-
>result()

returns the
query result

as an array of objects, or an empty array on failure
. The objects
are…


$db
-
>query
-
>
result_array()

returns a map, (the key: row number starting with 0, the value is the row as a object.


)


It sometimes cause problem with foreign reference when used in the get_all() function because the key is not the
object id but the row id.

Schema to
support M
odels

It is also up to the developer to create the schema for the database. Typically this is done is a file such as schema.sql.


It is a little different on schema between Grails and Codeigniter
with respect to

the schema.


In
CodeIgniter
, we'll

need to
create tables in schema first, but in Grails,
the schema is generated automatically.


ActiveRecord (at least in the CodeIgniter version) doesn’t provide cascade management directly, so you wll have to encode
it into the associations and indexes of

the database schema. For instance, if you turned on the cascade delete on a master
table, deleting a master record will cascade to delete all of the detail records.

To turn on the cascade delete, all we need

i
s
Page
4

of
21

to specify "ON DELETE CASCADE
" on all the
foreign reference
s,
for instance "FOREIGN KEY(question_id)
REFERENCES question(id) on DELETE

CASCADE"
.

Using Active Record

CodeIgniter uses a modified versio
n of the Active Record database p
attern.


This pattern allows information to be retrieved,
inserted
, and updated in your database with minimal scripting.


In some cases only one or two lines of code are necessary to
perform a database action.

CodeIgniter does not require that each database table be its own class file.

It instead provides a
more simpli
fied interface.


Beyond simplicity, a major benefit to using the Active Record features is that it allows you to create database independent
applications, since the query syntax is generated by each database adapter.

It also allows for safer queries, sinc
e the values
are escaped automatically by the system.


Note:


If you intend to write your own queries you can disable this class in your database config file, allowing the core
database library and adapter to utilize fewer resources.



Selecting Data



Inserting Data



Updating Data



Deleting Data



Method Chaining



Active Record Caching

$this
-
>db
-
>from();

Permits you to write the FROM portion of your query:


$this
-
>db
-
>select('title, content, date');

$this
-
>db
-
>from('mytable');


$query

= $this
-
>db
-
>get();


// Produces: SELECT title, content, date FROM mytable



Note: As shown earlier, the FROM portion of your query can be specified in the
$this
-
>db
-
>get()

function, so use
whichever method you prefer.

$this
-
>db
-
>join();

Permits you to wr
ite the JOIN portion of your query:


$this
-
>db
-
>select('*');

$this
-
>db
-
>from('blogs');

$this
-
>db
-
>join('comments', 'comments.id = blogs.id');


$query = $this
-
>db
-
>get();


// Produces:

// SELECT * FROM blogs

// JOIN comments ON comments.id = blogs.id


Mult
iple function calls can be made if you need several joins in one query.


If you need a specific type of JOIN you can specify it via the third parameter of the function. Options are: left, right, out
er,
inner, left outer, and right outer.


Page
5

of
21

$this
-
>db
-
>join('
comments', 'comments.id = blogs.id',
'left'
);


// Produces: LEFT JOIN comments ON comments.id = blogs.id


$this
-
>db
-
>where();

This function enables you to set
WHERE

clauses using one of four methods:


Note:

All values passed to this function are escaped au
tomatically, producing safer queries.

1.

Simple key/value method:

$this
-
>db
-
>where('name', $name);


// Produces: WHERE name = 'Joe'

Notice that the equal sign is added for you.

If you use multiple function calls they will be chained together with
AND

betwee
n them:

$this
-
>db
-
>where('name', $name);

$this
-
>db
-
>where('title', $title);

$this
-
>db
-
>where('status', $status);


// WHERE name = 'Joe' AND title = 'boss' AND status = 'active'

2.

Custom key/value method:


You can include an operator in the first parameter
in order to control the comparison:

$this
-
>db
-
>where('name !=', $name);

$this
-
>db
-
>where('id <', $id);


// Produces: WHERE name != 'Joe' AND id < 45

3.

Associative array method:

$array = array('name' => $name, 'title' => $title,
'status' => $status);


$this
-
>db
-
>where($array);


// Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'

You can include your own operators using this method as well:

$array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);


$this
-
>db
-
>where($array);


4.

Custom string:


You can write your own clauses manually:

$where = "name='Joe' AND status='boss' OR status='active'";


$this
-
>db
-
>where($where);


$this
-
>db
-
>where() accepts an optional third parameter.

If you set it to FALSE, CodeIgniter will not try to p
rotect your
field or table names with backticks.


$this
-
>db
-
>where('MATCH (field) AGAINST ("value")', NULL, FALSE);

Page
6

of
21

Configuration

The config.php file
is an integral part of your application, and
contains

a large number of parameters that
configure

the web
application, driving the function of functioning of the various libraries.

Time handling

The time reference used in now() and other functions is defined with the configuration attribute “time_reference”. The
default is GMT.

Pagination

Use the pagination l
ibrary, which is loaded with



$this
-
>library
-
>load(“pagination”);


Configure the library with:

<fill in>


Generate the links with:

<fill in>

URI Routing

Typically there is a one
-
to
-
one relationship between a URL string and its corresponding controller

class/method. The
segments in a URI normally follow this pattern:

example.com/
class
/
function
/
id
/



In some instances, however, you may want to remap this relationship so that a different class/function can be called instead
of the one corresponding to the

URL.


For example, let’s say you want your URLs to have this prototype:

example.com/product/1/

example.com/product/2/

example.com/product/3/

example.com/product/4/


Normally the second segment of the URL is reserved for the function name, but in the exam
ple above it instead has a
product ID.


To overcome this, CodeIgniter allows you to remap the URI handler.


Routing rules are defined in your
application/config/routes.php

file.


In it you'll see an array called
$route

that permits you
to specify your own
routing criteria.

Routes can either be specified using
wildcards

or
Regular Expressions


A typical wildcard route might look something like this:

$route['product/:num'] = "catalog/product_lookup";



In a route, the array key contains the URI to be matched
, while the array value contains the destination it should be re
-
routed to.


In the above example, if the literal word "product" is found in the first segment of the URL, and a number is
found in the second segment, the "catalog" class and the "product_loo
kup" method are instead used.


You can match literal values or you can use two wildcard types:


(:num)

will match a segment containing only numbers.

(:any)

will match a segment containing any character.


Note:

Routes will run in the order they are defined
.

Higher routes will always take precedence over lower ones.

Here are a few routing examples:

$route['journals'] = "blogs";


A URL containing the word "journals" in the first segment will be remapped to the "blogs"
controller
.

Page
7

of
21

$route['blog/joe'] = "blogs/
users/34";


A URL containing the segments blog/joe will be remapped to the "blogs"
controller

and the "users" method. The ID will be
set to "34".

$route['product/(:any)'] = "catalog/product_lookup";


A URL with "product" as the first segment, and anything
in the second will be remapped to the "catalog"
controller

and the
"product_lookup" method.


$route['product/(:num)'] = "catalog/product_lookup_by_id/$1";



A URL with "product" as the first segment, and a number in the second will be remapped to the "cata
log"
controller

and the
"product_lookup_by_id" method passing in the match as a variable to the function.


Important:

Do not use leading/trailing slashes.


If you prefer you can use regular expressions to define your routing rules. Any valid regular expres
sion is allowed, as are
back
-
references.


Note:


If you use back
-
references you must use the dollar syntax rather than the double backslash syntax.


A typical RegEx route might look something like this:


$route['products/([a
-
z]+)/(
\
d+)'] = "$1/id_$2";



In

the above example, a URI similar to
products/shirts/123

would instead call the
shirts

controller class and the
id_123

function.


You can also mix and match wildcards with regular expressions.


There are two reserved routes:


$route['default_controller'] =

'welcome';



This route indicates which controller class should be loaded if the URI contains no data, which will be the case when
people load your root URL. In the above example, the "welcome" class would be loaded. You are encouraged to always
have a de
fault route otherwise a 404 page will appear by default.


$route['404_override'] = '';



This route indicates which controller class should be loaded if the requested controller is not found. It will override the
default 404 error page. It won't affect to
the
show_404()

function, which will continue loading the default
error_404.php

file at
application/errors/error_404.php
.

Support functions for V
iews

If t
he

Url


Helper

is
loaded (typically in your controller), a set of functions will be available for work
ing with url’s,
anchors, and redirects in your site.


// Load the URL helper so redirects work.

$this
-
>load
-
>helper('url');


For example, i
f we
type



<?php echo anchor('crud_example/index', 'Admin Home'); ?>


We get


<
a

href
="
http://therisbergfamily.com/i
gniter/index.php/crud_example/index
"
>

Page
8

of
21


Admin Home

</
a
>

Support functions for Forms in V
iews

Other similar functions include generators for the start and end of forms. Plus there are few functions for form elements.
These don’t take the form of special t
ags in the JSP sense


this is because there is no processing like JSP elements


instead it is all PHP functions.

These include:


form_open()



used to generate the <form> tag, and the action for the form. Attributes include class, etc.


form_close()



used to generate the </form> tag


form_input()



this can produce several variations on input elements, here is an example:

<?php
echo
form_input('street', set_value('street', $street), 'size="50"') ?>


form_dropd
own(
name, options, value
)



this can produc
e the <select> dropdown and its <options>, here is an example:

<?php $options =
array
(


'discover' => 'Discover',


'visa' => 'Visa',


'americanExpress' => 'American Express',


'masterCard' => '
Master Card',


);



echo
form_dropdown('card_type', $options, set_value('card_type', $card_type));


?>


Note that these examples also use the set_value() function, which is handy for re
-
populating the form after a validation
error.


Our most advanced forms, such as the payment screen, make extensive use of these capabilities of the framework.

Form Validation

CodeIgniter contains a very powerful form validation system.


CodeIgniter lets you set as many validation rules as you need for

a given field, cascading them in order, and it even lets you
prep and pre
-
process the field data at the same time.

To set validation rules you will use the
set_rules()

function:


$this
-
>form_validation
-
>set_rules();



The above function takes
three

param
eters as input:

1.

The field name
-

the exact name you've given the form field.

2.

A "human" name for this field, which will be inserted into the error message. For example, if your field is named
"user" you might give it a human name of "Username".
Note:

If you

would like the field name to be stored in a
language file, please see
Translating Field Names
.

3.

The validation rules for this form field.

To run the validat
ion rules call:

<?php

class Form extends CI_Controller {



function index()


{


$this
-
>load
-
>helper(array('form', 'url'));


Page
9

of
21


$
this
-
>load
-
>library('form_validation');



$this
-
>form_validation
-
>set_rules('username', 'Username', 'required');


$t
his
-
>form_validation
-
>set_rules('password', 'Password', 'required');


$this
-
>form_validation
-
>set_rules('passconf', 'Password Confirmation', 'required');


$this
-
>form_validation
-
>set_rules('email', 'Email', 'required');



if ($this
-
>form_validatio
n
-
>run() == FALSE)


{


$this
-
>load
-
>view('myform');


}


else


{


$this
-
>load
-
>view('formsuccess');


}


}

}

?>


One detail that kept confusing me is that in the above code index() is called for the initial display of the form as we
ll as the
processing of results on the form. The answer is that $this
-
>form_validation
-
>run() simply returns false with no errors if
the HTTP request that is being processed is a GET, not a POST. Hence, the index() method is sm
art enough to handle both
c
ases, but it is implict in form_validation
-
>run() method.

Hooks

Hooks allow you to override the built
-
in processing of dispatching and view generation. This is slightly more advanced
topic than the others in this document, however, we mention it here beca
use the facility for creating Rails
-
like layouts uses
it.


To use hooks you must first enble it in the config file.


Then change the hooks.php file to define the handler for a given hook point. For instance:


$hook['pre_controller'] = array(



'class'

=> 'MyClass',


'function' => 'Myfunction',


'filename' => 'Myclass.php',


'filepath' => 'hooks',


'par
ams'

=> array('beer', 'wine', 'snacks')


);


The implementation of a hook goes into the “hooks” directory of your application (typically).

Layout Facility like in Rails

Based on the discussion in
http://codeigniter.com/forums/viewthread/57902/


We implemented a facility to specify a default layout in the views/layouts directory, where the layout looks like:


<!DOCTYPE html PUBLIC "
-
//W3C//DTD XHTML 1.0 Transiti
onal//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1
-
transitional.dtd">

<html xmlns=
"http://www.w3.org/1999/xhtml"
>

<head>


<meta http
-
equiv=
"Content
-
Type"

content=
"text/html; charset=utf
-
8"

/>


<title><?php
echo
$title;?></title>



<link rel=
"stylesheet"

href="<?php
echo
base_url();?>
assets/css/style.css
" type=
"text/css"

/>


</head>


<body>


<div id=
"container"
>


<?php $this
-
>load
-
>view('_header');?>

Page
10

of
21


<?php $this
-
>load
-
>view('_menu');?>


{yield}


<?php $this
-
>load
-
>view('_footer');
?>


</div>


</body>

</html>

Partial Views (also called template views in Grails)

In your view.php file, you can include another view simply by using “$this
-
>load
-
>view()” instead of ‘include()’.

This is
the easiest and most straight
-
forward solution
, and will be what you need in 90% of all cases.




By convention, we use the underscore prefix in the name of a partial view (this appears to be used in Rails and Grails as
well).


Note that whatever data you pass to the main parent view from your control
ler will be available to all nested views, too.

So, let us suppose that in your controller you do:


$data['copyright']

=

'2008,

My

Company';




Then, in your nested “
_
footer.php” view file, you could use that data like this:


<p>©<?=

$copyright

?>.</p>



Session
Management

The Session class permits you maintain a user's "state" and track their activity while they browse your site. The Session
class stores session information for each user as serialized (and optionally encrypted) data in a cookie. It can al
so store the
session data in a database table for added security, as this permits the session ID in the user's cookie to be matched agains
t
the stored session ID. By default only the cookie is saved. If you choose to use the database option you'll need to
create the
session table as indicated below.


Note:

The Session class does
not

utilize native PHP sessions. It generates its own session data, offering more flexibility for
developers.


Note:

Even if you are not using encrypted sessions, you must set an
encryption key

in your config file which is used to aid
in preventing session data manipulation.


A
session
, as far as CodeIgniter is concerned, is simply an array containing the fo
llowing information:



The user's unique Session ID (this is a statistically random string with very strong entropy, hashed with MD5 for
portability, and regenerated (by default) every five minutes)



The user's IP Address



The user's User Agent data (the first

120 characters of the browser data string)



The "last activity" time stamp.


The above data is stored in a cookie as a serialized array with this prototype:


[array]

(


'session_id'

=> random hash,


'ip_address'

=> 'string
-

user IP address',


'user_agent'

=> 'string
-

user agent data',


'last_activity' => timestamp

)



If you have the encryption option enabled, the serialized array will be encrypted before being stored in the cookie, making
the data highly secure and impervious to
being read or altered by someone. More info regarding encryption can be
found
here
, although the Session class will take care of initializing and encrypting the data automatically.

Page
11

of
21


Note: Session cookies are only updated every five minutes by default to reduce processor load.


If you repeatedly reload a
page you'll notice that the "last activity" time only updates if five minutes or more has passed since the last time the cook
ie
was

written.

This time is configurable by changing the $config['sess_time_to_update'] line in your
system/config/config.php file.


Code Igniter’s standard session library has many critics, enough to produce three or more competitors.

Whatever the critics
sa
y, most have agreed that the library does provide a neat interface to session handling, is simple and intuitive to use and
well documented.


Major weaknesses of the library
:





Security

: The User Data is stored in a cookie, client
-
side.





Security

:
The session is vulnerable to session fixation.





Usability

: Enabling the session database does not actually store User
-
Data in the database!





Usability

: Things like non
-
persistent sessions, flash variables and session id regeneration are not enabled
.


The original reason Rick wrote the custom library was to avoid unpredictable results with PHP’s configuration and setup
variances across hosts.

A custom library (should) provide the developer with finer control and dependability.

Retrieving Session Dat
a

Any piece of information from the session array is available using the following function:

$this
-
>session
-
>userdata('
item
');


Where
item

is the array index corresponding to the item you wish to fetch. For example, to fetch the session ID you will
do this
:

$session_id = $this
-
>session
-
>userdata('
session_id
');


Note:

The function returns FALSE (boolean) if the item you are trying to access does not exist.

Adding Custom Session Data

A useful aspect of the session array is that you can add your own data to it

and it will be stored in the user's cookie. Why
would you want to do this? Here's one example:


Let's say a particular user logs into your site. Once authenticated, you could add their username and email address to the
session cookie, making that data g
lobally available to you without having to run a database query when you need it.


To add your data to the session array involves passing an array containing your new data to this function:

$this
-
>session
-
>set_userdata(
$array
);


Where
$array

is an associat
ive array containing your new data. Here's an example:

$newdata = array(


'username'


=> 'johndoe',


'email'

=> 'johndoe@some
-
site.com',


'logged_in' => TRUE


);


$this
-
>session
-
>set_u
serdata(
$newdata
);

If you want to add userdata one value at a time, set_userdata() also supports this syntax.

$this
-
>session
-
>set_userdata('some_name', 'some_value');

Note:

Cookies can only hold 4KB of data, so be careful not to exceed the capacity. The e
ncryption process in particular
produces a longer data string than the original so keep careful track of how much data you are storing.

Replacing the

index.php in URLs

Use the rewrite facility within Apac
he. First it must be turned on in the Apache config
uration.

Page
12

of
21


Then write a .htaccess file such as:


<IfModule mod_rewrite.c>


RewriteEngine On


RewriteBase /
rubric



RewriteCond %{REQUEST_URI} ^system.*


RewriteRule ^(.*)$ /index.php?/$1 [L]




RewriteCond %{REQUEST_URI} ^application.*



RewriteRule ^(.*)$ /index.php?/$1 [L]



RewriteCond %{REQUEST_FILENAME} !
-
f


RewriteCond %{REQUEST_FILENAME} !
-
d


RewriteRule ^(.*)$ index.php?/$1 [L]

</IfModule>


Finally, change config.php file to have a

blan
k for the application path, such as:


$config[
'index_page'
] =
''
;

Template Processing (built in)

The Template Parser Class enables you to parse pseudo
-
variables contained within your view files. It can parse simple
variables or variable tag pairs. If you've never used a template engine, pseu
do
-
variables look like this:

<html>

<head>

<title>{blog_title}</title>

</head>

<body>


<h3>{blog_heading}</h3>


{blog_entries}

<h5>{title}</h5>

<p>{body}</p>

{/blog_entries}

</body>

</html>



These variables are not actual PHP variables, but rather plain t
ext representations that allow you to eliminate PHP from
your templates (view files).


$this
-
>load
-
>library('parser');


$data = array(


'blog_title' => 'My Blog Title',


'blog_heading' => 'My Blog Heading'


);


$this
-
>parse
r
-
>parse('blog_template', $data);

User Management

A

simple approach is described in
http://www.codefactorycr.com/login
-
with
-
codeigniter
-
php.html

this defines a controller
which
handles login and logout, and a validate method on the user_model to determine if a user is valid.


See more details below.

Page
13

of
21

Security Frameworks

The

Security


Helper file contains security related functions.


Keychain is a rule
-
based authorization library
for
CodeIgniter
. It has support for groups and can protect a controller's page
s
with just two lines.
It's designed to be simple of use, for use when you want basis a
uthenticati
on on your websites. See
more details below.


Another security framework is called ION. See
http://benedmunds.com/ion_auth/

Using UI libraries such as jQuery/jQueryUI

CodeIgniter itself is independent of t
he libraries used for the presentation, but use of jQuery and jQueryUI is quite
common.

Upload Management

See
http://net.tutsplus.com/tuto
rials/php/codeigniter
-
from
-
scratch
-
file
-
uploading
-
and
-
image
-
manipulation/

for a good
tutorial in this area.

The example includes uploading, and creating a thumbnail
-
size image for a gallery.

However, it is for
CodeIgniter version 1.7.


CodeIgniter's Fil
e Uploading Class permits files to be uploaded. You can set various preferences, restricting the type and
size of the files.

The page in which the user specifies what is to be upload must use a form_open
_multipart
()

tag.

Then
create a controller such as:


<?php

class Upload extends CI_Controller {



function __construct()

{



parent::__construct();



$this
-
>load
-
>helper(array('form', 'url'));


}



function index()

{



$this
-
>load
-
>view('upload_form', array('error' => ' ' ));


}



function do_upload()

{



$config['upload_path'] = './uploads/';



$config['allowed_types'] = 'gif|jpg|png';



$config['max_size']

= '100';



$config['max_width'] = '1024';



$config['max_height'] = '768';




$this
-
>load
-
>library('upload', $config);




if ( ! $this
-
>upload
-
>do_up
load())

{




$error = array('error' => $t
his
-
>upload
-
>display_errors());




$this
-
>load
-
>view('upload_form', $error);



}



E
lse

{




$data = array('upload_data' => $this
-
>upload
-
>data());




$this
-
>load
-
>view('upload_success', $data);



}


}

}

?>


The con
figuration is passed into the library using the load
-
>library call. Then we call do_upload(), this takes
‘user
file


as a
default parameter.


Page
14

of
21

The other functions are display_errors() and data(). See the reference page at
http://codeigniter.com/user_guide/libraries/file_uploading.html

for more details.

The following preferences are available. The default value indicates what will be used if you do not specify that preference.

P
reference

Default

Value

Options

Description

upload_path

None

None

The path to the folder where the upload should be placed. The folder must
be writable and the path can be absolute or relative.

allowed_types

None

None

The mime types corresponding to the
types of files you allow to be
uploaded. Usually the file extension can be used as the mime type.
Separate multiple types with a pipe.

file_name

None

Desired file name

If set CodeIgniter will rename the uploaded file to this name. The
extension provided i
n the file name must also be an allowed file type.

overwrite

FALSE

TRUE/FALSE
(boolean)

If set to true, if a file with the same name as the one you are uploading
exists, it will be overwritten. If set to false, a number will be appended to
the filename if

another with the same name exists.

max_size

0

None

The maximum size (in kilobytes) that the file can be. Set to zero for no
limit. Note: Most PHP installations have their own limit, as specified in
the php.ini file. Usually 2 MB (or 2048 KB) by default.

max_width

0

None

The maximum width (in pixels) that the file can be. Set to zero for no
limit.

max_height

0

None

The maximum height (in pixels) that the file can be. Set to zero for no
limit.

max_filename

0

None

The maximum length that a file name can b
e. Set to zero for no limit.

encrypt_name

FALSE

TRUE/FALSE
(boolean)

If set to TRUE the file name will be converted to a random encrypted
string. This can be useful if you would like the file saved with a name that
can not be discerned by the person uploa
ding it.

remove_spaces

TRUE

TRUE/FALSE
(boolean)

If set to TRUE, any spaces in the file name will be converted to
underscores. This is recommended.

Using Folders for uploaded files

You'll need a destination folder for your uploaded images. Create a fold
er at the root of your CodeIgniter installation called
uploads

and set its file permissions to 777.


To store into folders within that folder, use the upload_path preference value.

Image Manipulation

Library

CodeIgniter's Image Manipulation class lets you
perform the following actions:



Image Resizing



Thumbnail Creation



Image Cropping



Image Rotating



Image Watermarking

All three major image libraries are supported: GD/GD2, NetPBM, and ImageMagick

There is an example at
http://net.tutsplus.com/tutorials/php/codeigniter
-
from
-
scratch
-
file
-
uploading
-
and
-
image
-
manipulation/

Like most other classes in CodeIgniter, the image class is initialized in y
our controller using the
$this
-
>load
-
>library

function:

$this
-
>load
-
>library('image_lib');


Page
15

of
21

Once the library is loaded it will be ready for use.

The image library object you will use to call all functions is:
$this
-
>image_lib

Regardless of the type of pro
cessing you would like to perform (resizing, cropping, rotation, or watermarking), the general
process is identical.

You will set some preferences corresponding to the action you intend to perform, then call one of four
available processing functions.

Fo
r example, to create an image thumbnail you'll do this:

$config['image_library'] = 'gd2';

$config['source_image'] = '/path/to/image/mypic.jpg';

$config['create_thumb'] = TRUE;

$config['maintain_ratio'] = TRUE;

$config['width'] = 75;

$config['height'] = 50;


$this
-
>load
-
>library('image_lib', $config);


$this
-
>image_lib
-
>resize();



The above code tells the
image_resize

function to look for an image called
mypic.jpg

located in the
source_image

folder,
then create a thumbnail that is 75 X 50 pixels using the
GD2
image_library
.


Since the
maintain_ratio

option is enabled,
the thumb will be as close to the target
width

and
height

as possible while preserving the original aspect ratio.

The
thumbnail will be called
mypic_thumb.jpg

(because the create_thumb value
is true).


You can also specify the output directory, using the “new_image” attribute.


There are four available processing functions:



$this
-
>image_lib
-
>resize()



$this
-
>image_lib
-
>crop()



$this
-
>image_lib
-
>rotate()



$this
-
>image_lib
-
>watermark()



$this
-
>image
_lib
-
>clear()


The image resizing function lets you resize the original image, create a copy (with or without resizing), or create a
thumbnail image.


For practical purposes there is no difference between creating a copy and creating a thumbnail except a t
humb will have the
thumbnail marker as part of the name (ie, mypic_thumb.jpg).


All preferences listed in the table above are available for this function except these three: rotation_angle, x_axis, and
y_axis.


The resizing function will create a thumbnail

file (and preserve the original) if you set this preference to TRUE:


$config['create_thumb'] = TRUE;



This single preference determines whether a thumbnail is created or not.


The resizing function will create a copy of the image file (and preserve the
original) if you set a path and/or a new filename
using this preference:


$config['new_image'] = '/path/to/new_image.jpg';



Notes regarding this preference:



If only the new image name is specified it will be placed in the same folder as the original



If on
ly the path is specified, the new image will be placed in the destination with the same name as the original.



If both the path and image name are specified it will placed in its own destination and given the new name.


Page
16

of
21

If neither of the two preferences lis
ted above (create_thumb, and new_image) are used, the resizing function will instead
target the original image for processing.


See also:

http://www.jenssegers.be/blog/31/CodeIgniter
-
resizing
-
and
-
cropping
-
images
-
on
-
the
-
fly
-
continued

Caching library

A wrapp
er over file system
-
based caching, APC, or memcached.

Here is an example:


$this
-
>load
-
>driver('cache', array('adapter' => 'apc', 'backup' => 'file'));


if ( ! $foo = $this
-
>cache
-
>get('foo'))

{


echo 'Saving to the cache!<br />';


$foo = 'foobarb
az!';



// Save into the cache for 5 minutes


$this
-
>cache
-
>save('foo', $foo, 300);

}


echo $foo;


There are calls to get from cache,
save

into cache, clear cache, etc.

Modular Extensions library

This library (which implements the Hierarchical Mode
l View Controller design pattern), also makes the CodeIgniter PHP
framework modular. Modules are groups of independent components (typically, controller, model and view) arranged in
one application sub
-
directory that can be dropped into other CodeIgniter
applications.


See the documentation at
https://bitbucket.org/wiredesignz/codeigniter
-
modular
-
extensions
-
hmvc/wiki/Home


This library also requires a structura
l
chang
e in the project’s directories.


To use HMVC functionality, such as Modules::run(), controllers must extend the MX_Controller class.


To use Modular Separation only, without HMVC, controllers will extend the CodeIgniter Controller class.

You must u
se
PHP5 style constructors in yo
ur controllers,
i
.
e
.
:


<?php

class Xyz extends MX_Controller {



function __construct()

{


parent::__construct();


}

}


Modules::run() is designed for returning view partials, and it will return buffered output
(a view) from a controller. The
syntax for using modules::run is a URI style segmented string and unlimited variables.

Installation

1) Start with a clean CI install.

2) Set $config[‘base_url’] correctly for your installation.

3) Access the URL /index.php/w
elcome => shows Welcome to CodeIgniter

Page
17

of
21

4) Drop Modular Extensions third_party files into the CI 2.0 application/third_party directory.

5) Drop Modular Extensions core files into application/core, the MY_Controller.php file is not required unless you wish t
o
create your own Controller extension.

6) Access the URL /index.php/welcome => shows Welcome to CodeIgniter

7) Create module directory structure application/modules/welcome/controllers.

8) Move controller application/controllers/welcome.php to application
/modules/welcome/controllers/welcome.php.

9) Access the URL /index.php/welcome => shows Welcome to CodeIgniter

10) Create directory application/modules/welcome/views.

11) Move view application/views/welcome_message.php to application/modules/welcome/views/
welcome_message.php

12) Access the URL /index.php/welcome => shows Welcome to CodeIgniter

You should now have a running Modular Extensions installation.

Usage

Q. What is Modular HMVC, why should I use it?


A. Modular HMVC = Multiple MVC triads


This is mos
t useful when you need to load a view and its data within a view.

Think about adding a shopping cart to a page.
The shopping cart needs its own controller which may call a model to get cart data.

Then the controller needs to load the
data into a view.

S
o instead of the main controller handling the page and the shopping cart, the shopping cart MVC can be
loaded directly in the page.

The main controller doesn’t need to know about it, and is totally isolated from it.


In CI we can’t call more than 1 contro
ller per request. Therefore, to achieve HMVC, we have to simulate controllers.

It can
be done with libraries, or with this “Modular Extensions HMVC” contribution.

Notes

This doesn’t require a change to the directory structure of the project. Frameworks l
ike FUEL and Bonfire have directory
structure changes for other reasons.

Template library
(Phil Sturgeon)

CodeIgniter
-
Template is a Template library that helps your build complex views with CodeIgniter.

It has logic to work
with themes & modules and helps

add your title, meta
-
data, breadcrumbs and partial views.


This is a facility written by
Phil
Sturgeon

of the CI development team.


The capabilities of the template system are to:



use themes



contain a parser



support the lookup of partials



cache things

Lay
outs and Partials

Place the layouts into /layouts directory.


Place partials for metadata, header, footer into the /partials directory.

Page
18

of
21

Module Support

Not much to say here, other than it works perfectly with
Modular Extensions
.

If you
r

views or partials are in a module, and
you are currently browsing a URL that is a module, it will look there first.

Calling the Template API

When using Template, we see this construct quite of
ten:



$this
-
>
template
-
>title($this
-
>
module_details
[
'name'
],
'the rest of the page title'
)


-
>build(
'index'
, $data);


as the final line in most controller actions.


$this
-
>module_details[‘name’] gets the name.


Why does template
-
>title take two args? Ac
tually you can have any number, and the title() method cats them together with
a title separator between them (default is ‘ | ‘).


The build method takes the name of the view, then the data array, then has optional fields for
specifying ‘
echo


or

cache

o
f results.

Measuring Performance

There is a built
-
in profiler system that will give times and queries. Turn this on in the __constructor method of your
controller:


// Enable the output profiler so you can see the db queries run.

$this
-
>output
-
>enable_pro
filer(TRUE);



Page
19

of
21

Debugging

There is no way to write to a console during PHP processing, but the following utility function c
a
n be used to write the
local file system.


// WINDOWS
-
specific code
--

this must be changed to use platform
-
independent calls.

//

pu
blic function
debug($string) {


$handle = fopen(
"c:
\
debug
\
debug.txt"
,
"a"
);
//a: append only


fwrite( $handle, $string);


fwrite( $handle,
"
\
n"
);




fclose($handle);

}


If you place
this into a class, you will use

$this
-
>debug to refrence it.

Deployment No
tes

Our approach is to develop locally, then zip up the files, and unzip on the hosting server.


The following changes must be made to the deployed files:

1.

database.php: d
atabase name, db user name, and db password

2.

config.php: home URL of application

Ques
tions

Caching?


http://codesamplez.com/development/codeigniter
-
2
-
features

Appendix A: Librar
ies which we have found useful

Besides the Module Extensions

and Template libraries

(dis
cussed above), we found the following

to be useful
:



AMF



Authentication



Blogs



Charting



Community



Database


o

MDB2

o

Oracle



Dropbox API



E
-
mail



Files



File System



GitHub Updater



Google Maps



HTML



Mail



Mailchimp



Miscallenous



Netflix API



Networking



Pagination



PDF



Shippi
ng

Page
20

of
21



Table



YouTube API

Appendix B
:
Example Programs

CI01

This is a simple blog e
xample based on
http://blog.pisyek.com/2011/03/create
-
a
-
simple
-
blog
-
using
-
codeigniter
-
2
-
0
-
part
-
1/


Uses

two tables (
post

and comment), and very simple model
classes. Perhaps too simple, there was no admin mode.


[done] Basic setup

[done
] add the “layout facility” to simplify the views

CI02

More complete blogging example, with user management as well. For instance, comments can only be posted by logged in
use
rs. There is also an admin role which brings up additional screens.


[done] Basic setup

[done] add the “layout facility” to simplify the views

[done] drop in the admin screens for post, comment
, user

[in progress] user management

CI03

This builds on the p
rior examples to include a use of the Modular Extensions

library
. It contains an example use of JQuery.
It also replaces the standard text editor with a rich text editor
.


[done] Basic setup

[done
] add MX library

[done
] add jQuery

[in progress] add Rich
Text Editor

CI04

This builds on the prior example and shows how to use

the
MX

extensions

and the
Template
library

developed by Phil
Sturgeon
.


[done
] Basic setup

[done
] Define first theme

[
mostly done
] Change older controllers to use the theme

[not yet sta
rted] Define second theme

CI05

Extends CI01 to have a classification system for posts, to store the classification data in a database table that is effienct

to
update, and a cache area that is efficient for matching.


[
done
] Basic setup

and creation of 10
examples of content

[done
] classification management



copy the classify function from blog2 into CI05

[done
] matching management



find related content

[in progress] cache management


cache the commonly used content so that matching is more efficient.


Page
21

of
21

C
I06

Similar to CI02, since it has the layout facility, however this project uses the
Twitter

Bootstrap library
. The idea model is

based on “idea
-
sourcing” sites, with table for ideas and competitions.


[done
] Basic s
etup
, including support libraries

[in p
rogress] Create the visual style and implement theme.