PHP Frameworks and CodeIgniter

53
PHP Frameworks and Introduction to PHP Frameworks and Introduction to CodeIgniter CodeIgniter Presenter: [email protected]

description

CodeIgniter is an open source rapid development web application framework, for use in building dynamic web sites with PHP

Transcript of PHP Frameworks and CodeIgniter

Page 1: PHP Frameworks and CodeIgniter

PHP Frameworks and Introduction to PHP Frameworks and Introduction to CodeIgniterCodeIgniter

Presenter:[email protected]

Page 2: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

PrerequisitePrerequisite

OOP – Object Oriented Programming PHP MySQL

Page 3: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

What we discuss What we discuss

What is Framework ? Basic idea of Framework What is PHP Framework ? MVC Architecture MVC ( Model View Controller) Architecture What is CodeIgniter ???? Installation of CodeIgniter A Basic Application Development Of Codeigniter Making a Website - Demo Application Flow of CodeIgniter

CodeIgniter URL Controllers Views Models CodeIgniter Libraries Helpers

Q/A

Page 4: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

What is a Framework ?

A framework is a set of tools, libraries and classes intended for separating routine tasks into independent modules which can be used repeatedly.

The main aim of a framework is to allow software developers to focus on the tasks which are unique for each project instead of repetitive code.

Page 5: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Basic Idea Of Web Framework

A web application framework

Is a Software framework Designed to support the development of

Dynamic websites Web applications Web services

Aims to alleviate the overhead associated with common activities used in Web development.

Libraries for database access Templating frameworks Session management Often promote code reuse Many more …….

Page 6: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

What is a PHP Framework ?

PHP frameworks …. Streamline the development of web Provides a basic structure for which to build the web

applications. Help to promote rapid application development (RAD), which

saves you time, Helps build more stable applications, Reduce the amount of repetitive coding for developers. Ensure proper database interaction and coding on the

presentation layer. Allows you to spend more time creating the actual web

application, instead of spending time writing repetitive code.

Page 7: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Comparison of Frameworks

Source-http://www.phpframeworks.com/

Page 8: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Comparison Parameters

MVC: Indicates whether the framework comes with inbuilt support for a Model-View-Controller setup.

Multiple DB's: Indicates whether the framework supports multiple databases without having to change anything.

ORM: Indicates whether the framework supports an object-record mapper, usually an implementation of ActiveRecord.

DB Objects: Indicates whether the framework includes other database objects, like a TableGateWay.

Templates: Indicates whether the framework has an inbuilt template engine. Caching: Indicates whether the framework includes a caching object or some way

other way of caching. Validation: Indicates whether the framework has an inbuilt validation or filtering

component. Ajax: Indicates whether the framework comes with inbuilt support for Ajax. Auth Module: Indicates whether the framework has an inbuilt module for handling

user authentication. Modules: Indicates whether the framework has other modules, like an RSS feed

parser, PDF module or anything else (useful). EDP: Event Driven Programming.

Page 9: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Evolution of Web DevelopmentEvolution of Web Development

How you first started building websites.How you first started building websites.

Page 10: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Without MVCWithout MVC

Page 11: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Evolution of Web DevelopmentEvolution of Web Development

How you’re building websites now.How you’re building websites now.

Page 12: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Evolution of Web DevelopmentEvolution of Web Development

How you build websites with a frameworkHow you build websites with a framework

Page 13: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

MVC Architecture

Separates User Interface From Business Logic Model: All database-related work is done through the model file. View: The front-end view (here, HTML) design is contained in the view file. Controller: The Controller, the base of MVC, controls everything inside the application. You can use

Views and Models only through a Controller; without a Controller file, your CodeIgniter app will not run.

Page 14: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

CodeIgniter

CodeIgniter is based on the Model-View-Controller development pattern. MVC is a software approach that separates application logic from presentation.

Page 15: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Model-View-ControllerModel-View-Controller

The Model represents your data structures. Typically your model classes will contain functions that help you retrieve, insert, and update information in your database.

The View is the information that is being presented to a user. A View will normally be a web page, but in CodeIgniter, a view can also be a page fragment like a header or footer. It can also be an RSS page, or any other type of "page".

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.

Page 16: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

MVC PatternMVC Pattern

1. Your computer will send a request to the Controller2. The Controller will interact with the Model, making a demand.3. The Model will make the processing, then return some data to the Controller.4. The Controller will analyze the results (maybe needs some more data, and it will

make another request to another Model).5. Finally, the data will be sent to the view, which is interpreted by the webserver, and

will be displayed back in your browser.

Page 17: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

MVC Pattern – Example User LoginMVC Pattern – Example User Login

1. You enter on the login page, complete the fields and click Submit.2. The request is send to the controller, it will ask the model about your identity.3. The model analyze the data you sent (if you are already a member, if your data is

correct, etc.) and it will send an Accept or a Denial back to the controller.4. The Controller will analyze the Accept/Denial from the model, and will decide what

to do.5. Finally, it will send “a Welcome” to the view, which will be visible to you as a

Welcome page, or an error page.

Page 18: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

What is CodeIgniter ???

An Open Source Web Application Framework Nearly Zero Configuration MVC ( Model View Controller ) Architecture Multiple DB (Database) support DB Objects Templating Caching Modules Validation Rich Sets of Libraries for Commonly Needed Tasks Has a Clear, Thorough documentation

Page 19: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

CodeIgniter ?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.

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.

Page 20: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Why CodeIgniter ?Why CodeIgniter ?

It is very easy to learn, as it’s deeply documented and very easy to extend.

CodeIgniter is a very light PHP framework (2.2 MB including the entire documentation) compared with:

1. Zend Framework 1.10.2 Full – 24 MB 2. symfony 1.4.3 – 5.1 MB 3. CakePHP 1.2.6 – 4.5 MB

It lightning fast compared with other PHP Framework,

Page 21: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Application Flow Of CodeIgniterApplication Flow Of CodeIgniter

Figure : 2 [ Application Flow of CodeIgniter]

Page 22: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

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.

Application Flow Of CodeIgniterApplication Flow Of CodeIgniter

Page 23: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Installation of CodeIgniter

Requirements Web Server - Apache / PHP Support Web Server PHP – 4.3.2 or Higher Database – MySQL ( support for other DB exists )

Installation Download the latest version from www.codeigniter.com Extract it, and move the folder to your Web server’s DocumentRoot

(usually /var/www/). Rename the extracted codeigniter folder to ‘leave′ (application name).

Page 24: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Directory Structure of CodeIgniterDirectory Structure of CodeIgniter

• index.php - recieves all requests and routes to the right controllers classes and actions, parameters are included in the URL

• /system - contains all CodeIgniter classes and libraries provided by the framework

• /application - this is where your application code is located, including the model, view and controller classes

Page 25: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Configuration of CodeIgniter

Open “leave/config/config.php” and change base_url value to base url. For example: http://localhost/leave/

/var/www/leave/application/config/config.php $config['base_url'] = 'http://localhost/leave/'; #Default CodeIgniter URL

$config['index_page'] = 'index.php'; #Default index page.

Page 26: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Configuration of CodeIgniter -DB

To Use Database open “leave/application/config/database.php” and change necessary values. Usually you have to change: ‘hostname’, ‘username’, ‘password’, ‘datbase’.

/var/www/leave/application/config/database.php

Page 27: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Configuration of CodeIgniter – Autoload

autoload.php: This file automatically loads parameters at program start /var/www/leave/application/config/autoload.php Auto-load database library; others are session, email etc. Helpers are APIs that speed up your work. There are many, like ‘file’,

‘form’, etc.

Page 28: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

How to run a CI method

http://localhost/leave/index.php/hello/aboutpage

Your main controller file:/var/www/leave/application/controllers/hello.php

The name of a method in your controllerWhere you’ve installed CI

Page 29: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Database Test – Model

/var/www/leave/application/models/dbtest.php

Page 30: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Database Test – View

/var/www/leave/application/views/dbtestviews.php

Page 31: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Database Test – Controller

/var/www/leave/application/controllers/dbTestController.php

Page 32: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Making a Website – CI Demo

A typical website layout

Footer

Header

Content

Menu

Page 33: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Making a Website – CI Demo

File Structure

Page 34: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Demo – Create Controller

Make a file home.php within /var/www/mysite/application/controllers/home.php

Page 35: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Demo – Create Views - Header

Make a file header.php within /var/www/mysite/application/views/mysite_header.php

Page 36: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Demo – Create Views - Menu

Make a file mysite_menu.php within /var/www/mysite/application/views/mysite_menu.php

Page 37: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Demo – Create Views - Footer

Make a file mysite_menu.php within /var/www/mysite/application/views/mysite_footer.php

Page 38: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Demo – Putting Altogether

Make a file mysite_main.php within /var/www/mysite/application/views/mysite_main.php

Page 39: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Controller and View Sample

Page 40: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

ControllersControllers

A Class file resides under “application/controllers”

http:/localhost/myapp/index.php/first

<?php

class First extends Controller{function First() {

parent::Controller();}

function index() {echo “<h1> Hello CUET !! </h1> “;

}}

?>// Output Will be “Hello CUET!!”

• Note:• Class names must start with an Uppercase Letter.• In case of “constructor” you must use “parent::Controller();”

Page 41: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

ControllersControllers

In This Particular Code (Passing parameters)

<?php

class First extends Controller{

function index() {echo “<h1> Hello CUET !! </h1> “;

}

function message( $location ) {echo “<h2> Hello $location !! </h2>”;

}}

?>// Output Will be “Hello world !!”

http:/localhost/myapp/index.php/first/message/world

• Note:• The ‘Index’ Function always loads by default. Unless there is a second segment in the URL

Page 42: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

VIEWSVIEWS

A Webpage or A page Fragment Should be placed under “application/views” Never Called Directly

<html><title> My First CodeIgniter Project</title><body> <h1> Welcome ALL … To My .. ::: First Project ::: . . . </h1></body></html>

http://localhost/myapp/system/application/views/myview.php

42

Page 43: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

VIEWS

Calling a VIEW from Controller Data Passing to a VIEW from Controller

$this->load->view(‘myview’);

function index() {$var = array(

‘full_name’ => ‘Khalid C’,‘email’ => ‘[email protected]

);$this->load->view(‘myview’, $var);

}

<html><title> ..::Personal Info::.. </title><body>Full Name : <?php echo $full_name;?> <br />E-mail : <?=email;?> <br /></body></html>

Controller

View

Page 44: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

ModelsModels

Designed to work with Information of Database Models Should be placed Under “application/models/”

<?php

class Mymodel extend Model{function Mymodel() {

parent::Model();}function get_info() {

$query = $this->db->get(‘name’, 10); /*Using ActiveRecord*/return $query->result();

}}?>

Loading a Model inside a Controller

$this->load->model(‘mymodel’);$data = $this->mymodel->get_info();

Page 45: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Database handlingDatabase handling

CodeIgniter provides a simple way to access the database.

It encapsulates the underlying database (MySQL, Oracle, etc)

The connection handling is done by CodeIgniter and configured through: /application/config/database.php

Provides security through automatic escaping of inserted data, avoids Cross-Side Scripting (CSS) attacks

Initializing the Database Class$this->load->database();

Standard Query With Multiple Results$query = $this->db->query('SELECT name, email FROM

my_table');

foreach ($query->result() as $row)

{

echo $row->title;

echo $row->email;

}

echo 'Total Results: ' . $query->num_rows();

Database Configuration

$db['default']['hostname'] = 'localhost';

$db['default']['username'] = 'root';

$db['default']['password'] = 'sysadm123';

$db['default']['database'] = 'leave';

$db['default']['dbdriver'] = 'mysql';

$db['default']['dbprefix'] = '';

$db['default']['pconnect'] = TRUE;

Page 46: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Helpers

Simply a collection of functions in a particular category. Loading A Helper Inside a Controller

Array Date File HTML Smiley Text

URL Cookie Download Form Security String

Directory E-mail Inflector XML Parser Typography

$this->load->helper(‘helper_name’);

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

Page 47: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

HelpersHelpers

These are small PHP functions that provide shortcuts, to outsource often used code

Helper functions are located in /application/helpers/ For example formatting, text, url or form helpers Needs to be loaded through: $this->load->helper(‘name‘); For example, to load the URL Helper file,

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

$this->load->helper('url'); anchor("books/main","List of Books");

(<a href="books/main">List of Books </a> )

Page 48: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

HelpersHelpers

Form Helper form_open() form_open_multipart() form_input() form_textarea() form_checkbox() form_submit() form_close()

URL Helper site_url() base_url() anchor() anchor_popup() mailto()

Page 49: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

CodeIgniter Libraries

Special Purpose Classes Libraries are similar to helpers Loaded through: $this->load->library('classname'); The difference is that they encapsulate more complex

functionality, such as image processing, form validation handling, caching, etc.

Libraries allow to dynamically extend CodeIgniters functionality and extendability

Page 50: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

CodeIgniter LibrariesCodeIgniter Libraries

Special Purpose Classes

Benchmarking Database Encryption Calendaring

FTP Table File Uploading Email

Image Manipulation Pagination Input and Security HTML

Trackback Parser Session Template

Unit Testing User Agent URI Validation

$this->load->library(‘database’);

Loading CodeIgniter Library

Page 51: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

CodeIgniter LibrariesCodeIgniter Libraries

Database Library

function index() {

$this->load->library(‘database’);$rslt = $this->db->query(“select first_name from user_name”);foreach( $rslt->result() as $row_data)

echo $row_data->first_name . “<br />”;

}

Page 52: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Questions & AnswersQuestions & Answers

Page 53: PHP Frameworks and CodeIgniter

<?php

echo phpinfo();

?>PHP Frameworks and Introduction to Codeigniter [email protected]

Useful Links

http://codeigniter.com/user_guide/index.html