codeigniter & mvc

47
CodeIgniter & MVC Jamshid Hashimi Trainer, Cresco Solution http://www.jamshidhashimi.com [email protected] @jamshidhashimi ajamshidhashimi Afghanistan Workforce Development Program

Upload: jamshid-hashimi

Post on 20-Aug-2015

2.553 views

Category:

Technology


7 download

TRANSCRIPT

Page 1: CodeIgniter & MVC

CodeIgniter & MVC

Jamshid HashimiTrainer, Cresco Solution

http://www.jamshidhashimi.com [email protected] @jamshidhashimi ajamshidhashimi

Afghanistan Workforce Development Program

Page 2: CodeIgniter & MVC

Agenda

• Supported Features• Understanding MVC• Application Flow Chart• CodeIgniter URLS• CodeIgniter Controllers• Views• Models• Helpers• Libraries• Hooks

Page 3: CodeIgniter & MVC

Supported Feaures• Model-View-Controller Based System• Extremely Light Weight• Full Featured database classes with support for several platforms.• Active Record Database Support• Form and Data Validation• Security and XSS Filtering• Session Management• Email Sending Class. Supports Attachments, HTML/Text email,

multiple protocols (sendmail, SMTP, and Mail) and more.• Image Manipulation Library (cropping, resizing, rotating, etc.).

Supports GD, ImageMagick, and NetPBM

Page 4: CodeIgniter & MVC

Supported Feaures

• File Uploading Class• FTP Class• Localization• Pagination• Data Encryption• Benchmarking• Full Page Caching• Error Logging• Application Profiling• Calendaring Class• User Agent Class

Page 5: CodeIgniter & MVC

Supported Feaures

• Zip Encoding Class• Template Engine Class• Trackback Class• XML-RPC Library• Unit Testing Class• Search-engine Friendly URLs• Flexible URI Routing• Support for Hooks and Class Extensions• Large library of "helper" functions

Page 6: CodeIgniter & MVC

Understanding MVC

• CodeIgniter is based on the Model-View-Controller development pattern. MVC is a software approach that separates application logic from presentation. – The Model represents your data structures. – The View is the information that is being presented to

a user. – The Controller serves as an intermediary between the

Model, the View, and any other resources needed to process the HTTP request and generate a web page.

Page 7: CodeIgniter & MVC

Application Flow Chart

Page 8: CodeIgniter & MVC

CodeIgniter URLS

• By default, URLs in CodeIgniter are designed to be search-engine and human friendly.

• CodeIgniter uses a segment-based approach.

example.com/news/article/my_article

Page 9: CodeIgniter & MVC

CodeIgniter URLS

• The first segment represents the controller class that should be invoked.

• The second segment represents the class function, or method, that should be called.

• The third, and any additional segments, represent the ID and any variables that will be passed to the controller.

example.com/class/function/ID

Page 10: CodeIgniter & MVC

CodeIgniter URLS

• Removing index.php

RewriteEngine onRewriteCond $1 !^(index\.php|images|robots\.txt)RewriteRule ^(.*)$ /index.php/$1 [L]

Page 11: CodeIgniter & MVC

DEMO

Page 12: CodeIgniter & MVC

CodeIgniter Controllers

• A Controller is simply a class file that is named in a way that can be associated with a URI.

• When a controller's name matches the first segment of a URI, it will be loaded.

<?phpclass Blog extends CI_Controller {

public function index(){

echo 'Hello World!';}

}?>

Page 13: CodeIgniter & MVC

CodeIgniter Controllers

• The second segment of the URI determines which function in the controller gets called.

<?phpclass Blog extends CI_Controller {

public function index(){

echo 'Hello World!';}

public function comments(){

echo 'Look at this!';}

}?>

Page 14: CodeIgniter & MVC

CodeIgniter Controllers

• If your URI contains more then two segments they will be passed to your function as parameters.

<?phpclass Products extends CI_Controller { public function shoes($sandals, $id) { echo $sandals; echo $id; }}?>

Page 15: CodeIgniter & MVC

CodeIgniter Controllers

• Constructors are useful if you need to set some default values, or run a default process when your class is instantiated. Constructors can't return a value, but they can do some default work.

<?phpclass Blog extends CI_Controller { public function __construct() { parent::__construct(); // Your own constructor code }}?>

Page 16: CodeIgniter & MVC

DEMO

Page 17: CodeIgniter & MVC

Views

• A view is simply a web page, or a page fragment, like a header, footer, sidebar, etc. In fact, views can flexibly be embedded within other views (within other views, etc., etc.) if you need this type of hierarchy.

$this->load->view('view.php');

Page 18: CodeIgniter & MVC

Views

• CodeIgniter will intelligently handle multiple calls to $this->load->view from within a controller.

<?phpclass Page extends CI_Controller { function index() { $data['page_title'] = 'Your title'; $this->load->view('header'); $this->load->view('menu'); $this->load->view('content', $data); $this->load->view('footer'); }}?>

Page 19: CodeIgniter & MVC

Views

• Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading function.

$data = array( 'title' => 'My Title', 'heading' => 'My Heading', 'message' => 'My Message');$this->load->view('blogview', $data);

Page 20: CodeIgniter & MVC

Views

• The data array you pass to your view files is not limited to simple variables. You can pass multi dimensional arrays, which can be looped to generate multiple rows.

<?phpclass Blog extends CI_Controller {

function index(){

$data['todo_list'] = array('Clean House', 'Call Mom', 'Run Errands');

$data['title'] = "My Real Title";$data['heading'] = "My Real Heading";$this->load->view('blogview', $data);

}}?>

Page 21: CodeIgniter & MVC

Views

<html><head><title><?php echo $title;?></title></head><body><h1><?php echo $heading;?></h1><h3>My Todo List</h3><ul><?php foreach ($todo_list as $item):?><li><?php echo $item;?></li><?php endforeach;?></ul></body></html>

Page 22: CodeIgniter & MVC

DEMO

Page 23: CodeIgniter & MVC

Models

• Models are PHP classes that are designed to work with information in your database.

class Model_name extends CI_Model { function __construct() { parent::__construct(); }}

Page 24: CodeIgniter & MVC

Models

$this->load->model('Model_name');

$config['hostname'] = "localhost";$config['username'] = "myusername";$config['password'] = "mypassword";$config['database'] = "mydatabase";$config['dbdriver'] = "mysql";$config['dbprefix'] = "";$config['pconnect'] = FALSE;$config['db_debug'] = TRUE;

Page 25: CodeIgniter & MVC

DEMO

Page 26: CodeIgniter & MVC

Helpers

• Helpers, as the name suggests, help you with tasks. Each helper file is simply a collection of functions in a particular category.

• Unlike most other systems in CodeIgniter, Helpers are not written in an Object Oriented format. They are simple, procedural functions. Each helper function performs one specific task, with no dependence on other functions.

Page 27: CodeIgniter & MVC

Helpers

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

$this->load->helper( array('helper1', 'helper2', 'helper3') );

<?php echo anchor('blog/comments', 'Click Here');?>

Page 28: CodeIgniter & MVC

Helpers

• Extending Helpers– To "extend" Helpers, create a file in your

application/helpers/ folder with an identical name to the existing Helper, but prefixed with MY_

– The term "extend" is used loosely since Helper functions are procedural and discrete and cannot be extended in the traditional programmatic sense.

Page 29: CodeIgniter & MVC

DEMO

Page 30: CodeIgniter & MVC

Libraries

• All of the available libraries are located in your system/libraries folder.

$this->load->library('class name');

$this->load->library(array('email', 'table'));

Page 31: CodeIgniter & MVC

Libraries

• CodeIgniter permits your libraries to extend native classes if you simply need to add some functionality to an existing library. Or you can even replace native libraries just by placing identically named versions in your application/libraries folder. – You can create entirely new libraries.– You can extend native libraries.– You can replace native libraries.

Page 32: CodeIgniter & MVC

Libraries

• File names must be capitalized. For example: Myclass.php

• Class declarations must be capitalized. For example: class Myclass

• Class names and file names must match.

Page 33: CodeIgniter & MVC

Libraries<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Someclass { public function some_function() { }}/* End of file Someclass.php */

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

$this->someclass->some_function();

Page 34: CodeIgniter & MVC

Libraries

• You can use class constructor for initializing data

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');class Someclass { public function __construct($params) { // Do something with $params }}?>

Page 35: CodeIgniter & MVC

Libraries

• Utilizing CodeIgniter Resources

$CI =& get_instance();

$CI->load->helper('url');$CI->load->library('session');$CI->config->item('base_url');etc.

Page 36: CodeIgniter & MVC

Libraries

• Replacing Native Libraries with Your Versions– To use this feature you must name the file and the

class declaration exactly the same as the native library.

– Note that most native classes are prefixed with CI_.

class CI_Email {

}

Page 37: CodeIgniter & MVC

Libraries

• If all you need to do is add some functionality to an existing library - perhaps add a function or two - then it's overkill to replace the entire library with your version. In this case it's better to simply extend the class. Extending a class is nearly identical to replacing a class with a couple exceptions: – The class declaration must extend the parent class.– Your new class name and filename must be prefixed

with MY_

Page 38: CodeIgniter & MVC

Libraries

• The parent constructor must be called, whenever we want to have to use a constructor in our own library.

class MY_Email extends CI_Email { public function __construct() { parent::__construct(); }}

Page 39: CodeIgniter & MVC

Libraries

• Setting your own prefix– To set your own sub-class prefix, open your

application/config/config.php file and look for this item:

$config['subclass_prefix'] = 'MY_';

Page 40: CodeIgniter & MVC

DEMO

Page 41: CodeIgniter & MVC

Hooks

• CodeIgniter's Hooks feature provides a means to tap into and modify the inner workings of the framework without hacking the core files.– For example, you might want to run a script right

before your controllers get loaded, or right after, or you might want to trigger one of your own scripts in some other location.

$config['enable_hooks'] = TRUE;

Page 42: CodeIgniter & MVC

Hooks

• Hooks are defined in application/config/hooks.php file. Each hook is specified as an array with this prototype:

$hook['pre_controller'] = array('class' => 'MyClass','function' => 'Myfunction','filename' => 'Myclass.php','filepath' => 'hooks','params' => array('milk', 'tea',

'fruit'));

Page 43: CodeIgniter & MVC

Hooks• class The name of the class you wish to invoke. If you prefer to

use a procedural function instead of a class, leave this item blank.• function The function name you wish to call.• filename The file name containing your class/function.• filepath The name of the directory containing your script. Note:

Your script must be located in a directory INSIDE your application folder, so the file path is relative to that folder. For example, if your script is located in application/hooks, you will simply use hooks as your filepath. If your script is located in application/hooks/utilities you will use hooks/utilities as your filepath. No trailing slash.

• params Any parameters you wish to pass to your script. This item is optional.

Page 44: CodeIgniter & MVC

Hooks

• Hook Points– pre_system: Called very early during system execution. Only

the benchmark and hooks class have been loaded at this point. No routing or other processes have happened.

– pre_controller: Called immediately prior to any of your controllers being called. All base classes, routing, and security checks have been done.

– post_controller_constructor: Called immediately after your controller is instantiated, but prior to any method calls happening.

– post_controller: Called immediately after your controller is fully executed.

Page 45: CodeIgniter & MVC

Hooks– display_override: Overrides the _display() function, used to

send the finalized page to the web browser at the end of system execution. This permits you to use your own display methodology. Note that you will need to reference the CI superobject with $this->CI =& get_instance() and then the finalized data will be available by calling $this->CI->output->get_output()

– cache_override: Enables you to call your own function instead of the _display_cache() function in the output class. This permits you to use your own cache display mechanism.

– post_system: Called after the final rendered page is sent to the browser, at the end of system execution after the finalized data is sent to the browser.

Page 46: CodeIgniter & MVC

DEMO

Page 47: CodeIgniter & MVC

QUESTIONS?