Intro To Mvc Development In Php
-
Upload
funkatron -
Category
Technology
-
view
14.005 -
download
0
Transcript of Intro To Mvc Development In Php
Intro to MVC Development in PHPEd Finkler • http://funkatron.com • @funkatron#tekmvc • php|tek 2009
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
All About MVChttp://www.flickr.com/photos/airship/118352487/
What is MVC?
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
A Diagram
Controller
ModelView
The Model
"Represent knowledge"
The data/business functionality
The View
Visual representation of the model
The screens and widgets of app
Gets data from model & updates model
The Controller
Link between user and system
Responsible for intercepting user input
Passes user input to view via messages
Why Does MVC Help?
Separation of concerns
Don't mix your chocolate with my peanut butter
"Swappability"
Avoid tight coupling
MVC is not magic fairy dust
But understanding it and using itcan make you a better developer
Variations on MVC
http://short.ie/k2f9rk
http://www.flickr.com/photos/stevem78/2975614995/
MVPModel-View-Presenter (Dolphin Smalltalk variant)
Presenter primarily updates model
Presenter
ModelView
PAC
Presentation-Abstraction-Controller
Presentation ModelControl
Presentation ModelControl
Presentation ModelControl
Presentation ModelControlPresentation ModelControl
Light vs Heavy
Where does the logic go?
Event-driven vs direct calls
Observer pattern
Why CodeIgniter?http://www.flickr.com/photos/alternatewords/2332580309/
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?
Because you've gotta pick one, dammit
All of them have value*
* except Zend Framework
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)
CodeIgniter MVC Implementation
More of a Passive View Pattern
http://short.ie/5o7eg4
Controller
ModelView
CI application flow
Stolen from CI user guide
App components
Front controller
Routing
Security
Controller
Model
Library
Helper
Plugin
Scripts
View
Caching
Front controller
index.php
Routing
class Search extends Controller {
public function single($id) { // [...] }}
http://domain.com/index.php/controller/method/param
Security
Filtering or blocking unsafe input
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… }?>
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'));
Library
A class designed to work on related tasks
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){ // [...]}
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'];
Script
Other scripts the CI app might use
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 ?>
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);
Caching
Saves response to file
Serves up file contents if cache not expired
CI Basics
http://www.flickr.com/photos/canoafurada/395304306/
CI Structure
index.php
system application
base classes &built-in functionality
app-specific classes& functionality
front controllerpoints to system andapplication folders
CI Structure
default layout
CI Structure
custom layout
only index.php is under document root
The CI Object
$this inside controllers
The loader
$this->load->{view|library|model|helper|etc}('name');
CI Out of the box
The Welcome App
Put CI on the server
Load it in the browser
Why does Welcome load?
How URLs map
Trace with Xdebug/MacGDBp
Making a web application
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
Make a web APIhttp://www.flickr.com/photos/dunechaser/2429621774/
Web API for pop. est. DB
Let users query our DB via HTTP
Return results on JSON or serialized PHP
Libraries, Components, Logging and Caching
http://www.flickr.com/photos/metaphorge/515054465/
Autoloading
Make certain libs, models, helpers, etc available automatically
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();
Helpers
Make your own
application/helpers/name_helper.php
Add to existing
application/helpers/MY_name_helper.php
Example: PHP lang helper
Using non-CI components
The CI Way
Examples: Simplepie, Markdown
The dirty, bad way
require() that jazz
Caching
set cache path in config
make dir writable
enable caching in controller methods
Logging
set path in config
make dir writable
manual logging: log_message(level, msg)
Error handling
CI uses it's own error handler
Can block expected behavior
Example
Questions?@funkatron/#[email protected]
http://www.flickr.com/photos/deadhorse/508559841/