Intro To Mvc Development In Php

19,968 views

Published on

Published in: Technology
3 Comments
18 Likes
Statistics
Notes
No Downloads
Views
Total views
19,968
On SlideShare
0
From Embeds
0
Number of Embeds
96
Actions
Shares
0
Downloads
1,055
Comments
3
Likes
18
Embeds 0
No embeds

No notes for slide

Intro To Mvc Development In Php

  1. Intro to MVC Development in PHP Ed Finkler • http://funkatron.com • @funkatron #tekmvc • php|tek 2009
  2. Thee Agenda All 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
  3. All About MVC http://www.flickr.com/photos/airship/118352487/
  4. What is MVC?
  5. 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
  6. A Diagram Controller View Model
  7. The Model quot;Represent knowledgequot; The data/business functionality
  8. The View Visual representation of the model The screens and widgets of app Gets data from model & updates model
  9. The Controller Link between user and system Responsible for intercepting user input Passes user input to view via messages
  10. Why Does MVC Help?
  11. Separation of concerns Don't mix your chocolate with my peanut butter
  12. quot;Swappabilityquot; Avoid tight coupling
  13. MVC is not magic fairy dust But understanding it and using it can make you a better developer
  14. Variations on MVC http://short.ie/k2f9rk http://www.flickr.com/photos/stevem78/2975614995/
  15. MVP Model-View-Presenter (Dolphin Smalltalk variant) Presenter primarily updates model Presenter View Model
  16. PAC Presentation-Abstraction-Controller Presentation Control Model Presentation Control Model Presentation Control Model Presentation Control Model Presentation Control Model
  17. Light vs Heavy Where does the logic go?
  18. Event-driven vs direct calls Observer pattern
  19. http://www.flickr.com/photos/alternatewords/2332580309/ Why CodeIgniter?
  20. 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?
  21. Because you've gotta pick one, dammit
  22. All of them have value* * except Zend Framework
  23. 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)
  24. CodeIgniter MVC Implementation
  25. More of a Passive View Pattern Controller View Model http://short.ie/5o7eg4
  26. CI application flow Stolen from CI user guide
  27. App components Front controller Helper Routing Plugin Security Scripts Controller View Model Caching Library
  28. Front controller index.php
  29. Routing http://domain.com/index.php/controller/method/param class Search extends Controller { public function single($id) { // [...] } }
  30. Security Filtering or blocking unsafe input
  31. Controller The core of everything <?php class Site extends Controller { quot;Heavyquot;: you could do function Site() { parent::Controller(); everything in controller $this->load->library('session'); } public methods are function index() { available as actions from // mletters model is auto-loaded $rows = $this->mletters->getMany(10); URL $data['rows'] = $this->_prepData($rows); $this->load->view('index', $data); } private methods prefixed with “_” function _prepData($rows) { // do some cleanup on the data… } ?>
  32. Model ActiveRecord pattern available, not required Query binding $sql = quot;SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?quot;; $this->db->query($sql, array(3, 'live', 'Rick')); Don't like the DB layer? Use something else Zend_DB, Doctrine, DataMapper (http://bit.ly/ datamapper), IgniteRecord (http://bit.ly/igrec) …
  33. Library A class designed to work on related tasks
  34. 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) { // [...] }
  35. 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'];
  36. Script Other scripts the CI app might use
  37. View Build response to client CI Views are limited Uses plain PHP as templating lang <?php foreach ($rows as $row): ?> <li class=quot;letterquot;> <div class=quot;bodyquot;> <h3>Dear Zend,</h3> <p><?=$row->body?></p> </div> <div class=quot;metaquot;> <div class=quot;postedquot;> <a href=quot;<?=site_url('/site/single/'.$row->id)?>quot;>Posted <?=$row->posted?></a> </div> <div class=quot;favoritequot;>Liked by <?=$row->favorite_count?> person(s). <a href=quot;<?=site_url('/site/favorite/'.$row->id)?>quot;>I like this</a> </div> </div> </li> <?php endforeach ?>
  38. View Optional template markup $this->load->library('parser'); <html> $this->parser->parse('blog_template', $data); <head> <title>{blog_title}</title> </head> <body> <h3>{blog_heading}</h3> {blog_entries} <h5>{title}</h5> <p>{body}</p> Want a heavier template lang? {/blog_entries} Use one. </body> </html>
  39. Caching Saves response to file Serves up file contents if cache not expired
  40. CI Basics http://www.flickr.com/photos/canoafurada/395304306/
  41. CI Structure front controller index.php points to system and application folders system application base classes & app-specific classes built-in functionality & functionality
  42. CI Structure default layout
  43. CI Structure custom layout only index.php is under document root
  44. The CI Object $this inside controllers
  45. The loader $this->load->{view|library|model|helper|etc}('name');
  46. CI Out of the box
  47. The Welcome App Put CI on the server Load it in the browser Why does Welcome load? How URLs map Trace with Xdebug/MacGDBp
  48. Making a web application
  49. 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
  50. Make a web API http://www.flickr.com/photos/dunechaser/2429621774/
  51. Web API for pop. est. DB Let users query our DB via HTTP Return results on JSON or serialized PHP
  52. http://www.flickr.com/photos/metaphorge/515054465/ Libraries, Components, Logging and Caching
  53. Autoloading Make certain libs, models, helpers, etc available automatically
  54. 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();
  55. Helpers Make your own application/helpers/name_helper.php Add to existing application/helpers/MY_name_helper.php Example: PHP lang helper
  56. Using non-CI components The CI Way Examples: Simplepie, Markdown The dirty, bad way require() that jazz
  57. Caching set cache path in config make dir writable enable caching in controller methods
  58. Logging set path in config make dir writable manual logging: log_message(level, msg)
  59. Error handling CI uses it's own error handler Can block expected behavior Example
  60. Questions? http://www.flickr.com/photos/deadhorse/508559841/ @funkatron/#tekmvc coj@funkatron.com

×