intro to mvc development in php

60
Intro to MVC Development in PHP Ed Finkler • http://funkatron.com • @funkatron #tekmvc • php|tek 2009

Upload: funkatron

Post on 07-May-2015

14.011 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Intro To Mvc Development In Php

Intro to MVC Development in PHPEd Finkler • http://funkatron.com • @funkatron#tekmvc • php|tek 2009

Page 2: Intro To Mvc Development In Php

Thee AgendaAll About MVC

Why CodeIgniter?

The CI MVC Model

CI Basics

Running CI out of the box

Making a basic web app

Making a web api

Libraries, components, logging and caching

Page 3: Intro To Mvc Development In Php

All About MVChttp://www.flickr.com/photos/airship/118352487/

Page 4: Intro To Mvc Development In Php

What is MVC?

Page 5: Intro To Mvc Development In Php

What is MVC?

1979, Norwegian, Xerox Parc

Give user the impression of interacting directly with data

Used in GUI apps first

http://short.ie/g95zua

Page 6: Intro To Mvc Development In Php

A Diagram

Controller

ModelView

Page 7: Intro To Mvc Development In Php

The Model

"Represent knowledge"

The data/business functionality

Page 8: Intro To Mvc Development In Php

The View

Visual representation of the model

The screens and widgets of app

Gets data from model & updates model

Page 9: Intro To Mvc Development In Php

The Controller

Link between user and system

Responsible for intercepting user input

Passes user input to view via messages

Page 10: Intro To Mvc Development In Php

Why Does MVC Help?

Page 11: Intro To Mvc Development In Php

Separation of concerns

Don't mix your chocolate with my peanut butter

Page 12: Intro To Mvc Development In Php

"Swappability"

Avoid tight coupling

Page 13: Intro To Mvc Development In Php

MVC is not magic fairy dust

But understanding it and using itcan make you a better developer

Page 14: Intro To Mvc Development In Php

Variations on MVC

http://short.ie/k2f9rk

http://www.flickr.com/photos/stevem78/2975614995/

Page 15: Intro To Mvc Development In Php

MVPModel-View-Presenter (Dolphin Smalltalk variant)

Presenter primarily updates model

Presenter

ModelView

Page 16: Intro To Mvc Development In Php

PAC

Presentation-Abstraction-Controller

Presentation ModelControl

Presentation ModelControl

Presentation ModelControl

Presentation ModelControlPresentation ModelControl

Page 17: Intro To Mvc Development In Php

Light vs Heavy

Where does the logic go?

Page 18: Intro To Mvc Development In Php

Event-driven vs direct calls

Observer pattern

Page 19: Intro To Mvc Development In Php

Why CodeIgniter?http://www.flickr.com/photos/alternatewords/2332580309/

Page 20: Intro To Mvc Development In Php

Why not CakePHP or Zend Framework or Limonade or Symfony or Solar or Kohana or Zoop or Yii or Akelos or PHP on Trax or Prado or Seagull?

Page 21: Intro To Mvc Development In Php

Because you've gotta pick one, dammit

Page 22: Intro To Mvc Development In Php

All of them have value*

* except Zend Framework

Page 23: Intro To Mvc Development In Php

That being said, CI is…Easy to understand

Simple

doesn't require advanced OOP

Doesn't force lots of conventions

Plays well with others

Quick to get up and running

Good docs and great community

Backed by invested entity (http://ellislab.com)

Page 24: Intro To Mvc Development In Php

CodeIgniter MVC Implementation

Page 25: Intro To Mvc Development In Php

More of a Passive View Pattern

http://short.ie/5o7eg4

Controller

ModelView

Page 26: Intro To Mvc Development In Php

CI application flow

Stolen from CI user guide

Page 27: Intro To Mvc Development In Php

App components

Front controller

Routing

Security

Controller

Model

Library

Helper

Plugin

Scripts

View

Caching

Page 28: Intro To Mvc Development In Php

Front controller

index.php

Page 29: Intro To Mvc Development In Php

Routing

class Search extends Controller {

public function single($id) { // [...] }}

http://domain.com/index.php/controller/method/param

Page 30: Intro To Mvc Development In Php

Security

Filtering or blocking unsafe input

Page 31: Intro To Mvc Development In Php

ControllerThe core of everything

"Heavy": you could do everything in controller

public methods are available as actions from URL

private methods prefixed with “_”

<?phpclass Site extends Controller {

function Site() { parent::Controller(); $this->load->library('session'); } function index() { // mletters model is auto-loaded $rows = $this->mletters->getMany(10); $data['rows'] = $this->_prepData($rows); $this->load->view('index', $data); } function _prepData($rows) { // do some cleanup on the data… }?>

Page 32: Intro To Mvc Development In Php

Model

ActiveRecord pattern available, not required

Query binding

Don't like the DB layer? Use something else

Zend_DB, Doctrine, DataMapper (http://bit.ly/datamapper), IgniteRecord (http://bit.ly/igrec) …

$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";$this->db->query($sql, array(3, 'live', 'Rick'));

Page 33: Intro To Mvc Development In Php

Library

A class designed to work on related tasks

Page 34: Intro To Mvc Development In Php

Helper

Procedural funcs, grouped by file

Mostly for views; available in controllers

/** * Plural * * Takes a singular word and makes it plural * * @access public * @param string * @param bool * @return str */ function plural($str, $force = FALSE){ // [...]}

Page 35: Intro To Mvc Development In Php

Plugin

Single procedural function

More extensive functionality than helper

$vals = array( 'word' => 'Random word', 'img_path' => './captcha/', 'img_url' => 'http://example.com/captcha/', 'font_path' => './system/fonts/texb.ttf', 'img_width' => '150', 'img_height' => 30, 'expiration' => 7200 );

$cap = create_captcha($vals);echo $cap['image'];

Page 36: Intro To Mvc Development In Php

Script

Other scripts the CI app might use

Page 37: Intro To Mvc Development In Php

ViewBuild response to clientCI Views are limitedUses plain PHP as templating lang

<?php foreach ($rows as $row): ?> <li class="letter"> <div class="body"> <h3>Dear Zend,</h3> <p><?=$row->body?></p> </div> <div class="meta"> <div class="posted"> <a href="<?=site_url('/site/single/'.$row->id)?>">Posted <?=$row->posted?></a> </div> <div class="favorite">Liked by <?=$row->favorite_count?> person(s). <a href="<?=site_url('/site/favorite/'.$row->id)?>">I like this</a> </div> </div> </li><?php endforeach ?>

Page 38: Intro To Mvc Development In Php

View

Optional template markup

Want a heavier template lang? Use one.

<html><head><title>{blog_title}</title></head><body>

<h3>{blog_heading}</h3>

{blog_entries} <h5>{title}</h5> <p>{body}</p> {/blog_entries}</body></html>

$this->load->library('parser');$this->parser->parse('blog_template', $data);

Page 39: Intro To Mvc Development In Php

Caching

Saves response to file

Serves up file contents if cache not expired

Page 40: Intro To Mvc Development In Php

CI Basics

http://www.flickr.com/photos/canoafurada/395304306/

Page 41: Intro To Mvc Development In Php

CI Structure

index.php

system application

base classes &built-in functionality

app-specific classes& functionality

front controllerpoints to system andapplication folders

Page 42: Intro To Mvc Development In Php

CI Structure

default layout

Page 43: Intro To Mvc Development In Php

CI Structure

custom layout

only index.php is under document root

Page 44: Intro To Mvc Development In Php

The CI Object

$this inside controllers

Page 45: Intro To Mvc Development In Php

The loader

$this->load->{view|library|model|helper|etc}('name');

Page 46: Intro To Mvc Development In Php

CI Out of the box

Page 47: Intro To Mvc Development In Php

The Welcome App

Put CI on the server

Load it in the browser

Why does Welcome load?

How URLs map

Trace with Xdebug/MacGDBp

Page 48: Intro To Mvc Development In Php

Making a web application

Page 49: Intro To Mvc Development In Php

Population estimates DB

Get our data from Numbrary: http://short.ie/w3f6h3)

Make a new controller

Change the default route

Config DB settings

Make a model

Make a view

Make fancier views

Page 50: Intro To Mvc Development In Php

Make a web APIhttp://www.flickr.com/photos/dunechaser/2429621774/

Page 51: Intro To Mvc Development In Php

Web API for pop. est. DB

Let users query our DB via HTTP

Return results on JSON or serialized PHP

Page 52: Intro To Mvc Development In Php

Libraries, Components, Logging and Caching

http://www.flickr.com/photos/metaphorge/515054465/

Page 53: Intro To Mvc Development In Php

Autoloading

Make certain libs, models, helpers, etc available automatically

Page 54: Intro To Mvc Development In Php

Libraries

Extending core libs

application/libraries/MY_Library.php

Replacing core libs

application/libraries/CI_Library.php

Creating your own libs

application/libraries/Library.php

Constructor: Library();

Page 55: Intro To Mvc Development In Php

Helpers

Make your own

application/helpers/name_helper.php

Add to existing

application/helpers/MY_name_helper.php

Example: PHP lang helper

Page 56: Intro To Mvc Development In Php

Using non-CI components

The CI Way

Examples: Simplepie, Markdown

The dirty, bad way

require() that jazz

Page 57: Intro To Mvc Development In Php

Caching

set cache path in config

make dir writable

enable caching in controller methods

Page 58: Intro To Mvc Development In Php

Logging

set path in config

make dir writable

manual logging: log_message(level, msg)

Page 59: Intro To Mvc Development In Php

Error handling

CI uses it's own error handler

Can block expected behavior

Example