Upgrade to Pro — share decks privately, control downloads, hide ads and more …

COMM2735 Guest Lecture -- Practical PHP: Framew...

njlbenn
April 26, 2012

COMM2735 Guest Lecture -- Practical PHP: Frameworks, Libraries, and Professional Practice

Guest Lecture for the COMM2735 (Dynamic Web Programming) module of the undergraduate New Media programme in the Institute of Communications Studies, University of Leeds

njlbenn

April 26, 2012
Tweet

More Decks by njlbenn

Other Decks in Programming

Transcript

  1. Short bio Research Fellow on an EU-funded project Background in

    Applied Computer Science Knowledge Representation The “Linked Data” Web Argument Visualisation In a nutshell I experiment with software to solve interesting problems Confession: I am not a PHP expert But I have learned a few things that might be helpful to you
  2. Purpose of talk Introduce the idea of Separation of Concerns

    Introduce frameworks in general, and Model-View-Controller (MVC) PHP frameworks as way of enabling rapid development that still achieves important separation of concerns. Introduce some popular PHP libraries Introduce important professional practice
  3. Separation of Concerns Code responsible for different aspects of the

    system should be separated Commonly, we want to separate code that deals with what is called the “business logic” (processing data and generating information) from code that deals with the presentation of information to the user. Separating code in this way is essential if different developers are working on different parts (e.g. backend developer working on business logic and frontend developer working on client views)
  4. Separation of Concerns – Example Bad Separation index.php <?php //

    Connect to database $link = mysql_connect('localhost ', 'comm2735user ', 'comm2735password '); mysql_select_db ('simpleblogdb ', $link); // Perform SQL query $result = mysql_query('SELECT id , title , created FROM posts ', $link); ?> <html > <head > <title >Blog posts </title > </head > <body > <h1 >Blog posts </h1 >
  5. Separation of Concerns – Example Bad Separation (cont’d) <table >

    <tr ><th >Id </th ><th >Title </th ><th >Created </th ></tr > <?php // Printing results in HTML while ($row = mysql_fetch_array ($result , MYSQL_ASSOC)) { echo "\t<tr >\n"; printf("\t\t<td > %s </td >\n", $row['id']); printf("\t\t<td > %s </td >\n", $row['title ']); printf("\t\t<td > %s </td >\n", $row['created ']); echo "\t</tr >\n"; } ?> </table > </body > </html > <?php // Closing connection mysql_close($link); ?>
  6. Separation of Concerns – Example Bad Separation (cont’d) HTML and

    PHP code are tightly interwoven, which makes it tedious to make changes to presentation of information (especially if we want to give to a frontend specialist)
  7. Separation of Concerns – Separate Presentation index.php <?php // Connect

    to database $link = mysql_connect('localhost ', 'comm2735user ', 'comm2735password '); mysql_select_db ('simpleblogdb ', $link); // Perform SQL query $result = mysql_query('SELECT id , title , created FROM posts ', $link); // Fill up the array for the view $posts = array (); while ($row = mysql_fetch_array ($result , MYSQL_ASSOC)) { $posts [] = $row; }
  8. Separation of Concerns – Separate Presentation (cont’d) // Closing connection

    mysql_close($link); // Require the view require('index_view.php'); ?>
  9. Separation of Concerns – Separate Presentation (cont’d) index_view.php <html >

    <head > <title >Blog posts </title > </head > <body > <h1 >Blog posts </h1 > <table > <tr ><th >Id </th ><th >Title </th ><th >Created </th ></tr > <?php foreach ($posts as $post): ?> <tr > <td ><?php echo $post['id'] ?></td > <td ><?php echo $post['title '] ?></td > <td ><?php echo $post['created '] ?></td > </tr > <?php endforeach; ?> </table > </body > </html >
  10. Separation of Concerns – Templating Engines One early approach to

    enforcing SoC was to use specialised templating engines to go beyond PHP’s own templating features. One leading PHP templating engine is Smarty (http://www.smarty.net/), which introduces its own cleaner syntax so that frontend specialists and designers do not need to deal with intricacies of PHP code. But critics of templating systems question whether the effort of learning a new syntax and the overhead of loading a templating engine and parsing specialise templates is justified.
  11. Separation of Concerns – Smarty Template Example index.tpl <html >

    <head > <title >Blog posts </title > </head > <body > <h1 >Blog posts </h1 > <table > <tr ><th >Id </th ><th >Title </th ><th >Created </th ></tr > {foreach $posts as $post} <tr > <td >{ $post.id}</td > <td >{ $post.title}</td > <td >{ $post.created }</td > </tr > {/ foreach} </table > </body > </html >
  12. Separation of Concerns – MVC architectural pattern The current, most

    common way of enforcing SoC is to structure the entire system using what is called the Model-View-Controller architectural pattern
  13. Brief introduction to MVC First introduced in the late 1970s

    by a computer scientist called Trygve Reenskaug The original MVC pattern as proposed by Reenskaug is rarely adhered to. Instead a derivative form has been adapted for Web development. In Web development, MVC helps us separate the concerns of client-side presentation, server-side input-handling, and the application’s business logic.
  14. Brief introduction to MVC (cont’d) Model A Model contains the

    server-side business logic. Typically a Model maps to a database table and handles reading and writing to the database table. By convention a Book model would map to the books table. View A View is the output of a task or query that is rendered to the browser (i.e. HTML and associated client-side scripts and CSS). Controller A Controller contains one or more actions, each of which responds to an external request by querying the appropriate Model for information and then rendering the appropriate View.
  15. Separation of Concerns – MVC example posts_model.php <?php function getAllPosts

    () { // Connecting , selecting database $link = mysql_connect ('localhost ', 'comm2735user ', 'comm2735password '); mysql_select_db ('simpleblogdb ', $link); // Performing SQL query $result = mysql_query('SELECT id , title , created FROM posts ', $link); // Filling up the array $posts = array (); while ($row = mysql_fetch_array ($result , MYSQL_ASSOC)) { $posts [] = $row; }
  16. Separation of Concerns – MVC example (cont’d) index.php <?php //

    Require the model require('posts_model.php'); // Retrieve the list of posts $posts = getAllPosts (); // Require the view require('index_view.php'); ?>
  17. PHP Frameworks A PHP Framework is a set of PHP

    classes and functions that are bundled and configured together so they can be reused to develop a web application These classes and functions provide functionality that is common across most web applications – e.g. database access, form validation, etc. A framework is a generic foundation for building web applications that meet specific requirements
  18. Benefit of frameworks Most PHP frameworks follow an MVC architectural

    pattern so using a framework allows you to rapidly deploy a well-structured well application with good separation of concerns. Reduce repetitive coding Hide the details of managing database connection (and most frameworks support multiple database engines – MySQL, Oracle, etc.) Hide the details of accessing the database so no need to explicitly write SQL code (especially helpful when retrieving data that requires joining tables in the database) Built-in ways of handling common tasks such as form-validation, caching, user-management, URL re-writing
  19. Disadvantages of frameworks For very small applications a framework may

    add unnecessary overhead of downloading, installing, and configuring. It becomes a commitment, another system to learn. Switching to a new framework (or even new version of same framework) often means throwing out code and forgetting what you have learned to start from scratch. This makes code less reusable which defeats one of the purposes of using frameworks in first place. The framework itself may introduce bugs
  20. Example PHP frameworks There are literally dozens of PHP frameworks

    The website http://www.phpframeworks.com/ maintains a table comparing the features supported by each framework The “big four” are: CakePHP http://cakephp.org/ CodeIgniter http://codeigniter.com/ Symfony http://symfony.com/ Zend http://framework.zend.com/
  21. Choosing a framework All the leading contenders have good features

    to recommend them Choosing a framework may often come down to personal preferences CakePHP and CodeIgniter are generally thought to be easier to learn than Symfony and Zend If it is a career consideration then perhaps Zend is the most sought after by potential employers.
  22. Example Simple Blog Application in CakePHP app/Config/database.php <?php class DATABASE_CONFIG

    { public $default = array( 'datasource ' => 'Database/MySql ', 'persistent ' => false , 'host ' => 'localhost ', 'login ' => 'comm2735user ', 'password ' => 'comm2735password ', 'database ' => 'simpleblogdb ', 'prefix ' => '' ); }
  23. Example Simple Blog Application in CakePHP (cont’d) app/Controller/PostsController.php <?php class

    PostsController extends AppController { var $helpers = array ('Html ','Form '); var $name = 'Posts '; function index () { $this ->set('posts ', $this ->Post ->find('all')); } } ?>
  24. Example Simple Blog Application in CakePHP (cont’d) app/View/Posts/index.ctp <h1 >Blog

    posts </h1 > <table > <tr > <th >Id </th > <th >Title </th > <th >Created </th > </tr > <?php foreach ($posts as $post): ?> <tr > <td ><?php echo $post['Post ']['id']; ?></td > <td ><?php echo $post['Post ']['title ']; ?></td > <td ><?php echo $post['Post ']['created ']; ?></td > </tr > <?php endforeach; ?> </table >
  25. Enabling code reuse Just like frameworks, but at a different

    granularity, libraries and packages allow developers to reuse code functionality across various applications Libraries hide (or encapsulate) their internal workings and all the developer needs to worry about is the Application Programming Interface (API) that the library provides in order to communicate with its code to achieve the functionality Many libraries for useful tasks such as parsing XML or JSON documents are built into PHP. But they are other useful third-party libraries
  26. Useful and popular libraries reCAPTCHA A library for placing a

    CAPTCHA on your website to distinguish human users from bots. The library is a wrapper for Google’s reCAPTCHA API http://code.google.com/p/recaptcha/ API examples: echo recaptcha_get_html($publickey, $error); $response = recaptcha_check_answer($privatekey, $_SERVER[’REMOTE_ADDR’], $_POST[’recaptcha_challenge_field’], $_POST[’recaptcha_response_field’]); $response->is_valid
  27. Useful and popular libraries (cont’d) PHPExcel A library for writing

    to and reading from various spreadsheet formats, including XLS, CSV, and ODS http://www.phpexcel.net/ API examples: $excel = new PHPExcel(); $excel->getProperties()->setCreator(‘Neil Benn’); $excel->getProperties()->setTitle(‘World’s Greatest Spreadsheet’); $excel->getActiveSheet()->SetCellValue(‘A1’, ‘Hello’);
  28. Useful and popular libraries (cont’d) TCPDF A library for generating

    PDF documents http://www.tcpdf.org/ API examples: $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, ‘UTF-8’, false); $pdf->SetAuthor(‘Neil Benn’); $pdf->SetTitle(‘World’s Greatest PDF document’); $pdf->AddPage(); $pdf->Output(‘world-greatest.pdf’, ‘I’);
  29. Useful and popular libraries (cont’d) XAJAX A library for writing

    AJAX applications with minimal JavaScript, while staying in the PHP environment. http://www.xajaxproject.org/ API examples: $xajax = new xajax(); $xajax->register(XAJAX_FUNCTION, ‘doAdd’); function doAdd($a, $b) {...} $xajax->processRequest(); . . . onclick=”xajax_doAdd(10,600);”
  30. Library and package-management systems PEAR PEAR is a longstanding system

    for managing and distributing reusable PHP libraries You need to install the PEAR package manager on your local machine and then run commands from the manager that retrieve packages from the Internet But some PHP developers dislike PEAR (e.g. http://philsturgeon.co.uk/blog/2012/03/packages-the-way- forward-for-php) “Of the packages already on on PEAR, most of them are massively out of date, inactive and no longer maintained, or never made it out of alpha.”
  31. Library and package-management systems (cont’d) Composer http://getcomposer.org/ Composer is a

    tool for dependency management in PHP. It allows you to declare the dependent libraries your project needs and it will install them in your project for you. It differs from PEAR in that it doesn’t load packages globally on your computer; but rather installs libraries on a per-project basis in folders specific to a particular project You also need to download and install Composer on your local machine Has an associated repository called Packagist http://packagist.org/ Framework-specific package-management systems Sparks for CodeIgniter The Bakery for CakePHP Modules for Zend Framework
  32. Importance of readable code More time will be spent reading

    your code than writing it You or someone else will have to maintain and extend your code There is nothing more irritating than wading through ugly legacy code. Code formatting is important Communicating your code is just as important as getting it to work
  33. General rules-of-thumb Short files are usually easier to read than

    long ones Use vertical space to separate groups of statements (just like you would separate paragraphs in prose) Keep lines short (80 characters has become de facto standard, but anywhere from 45–80 is fine. Over 100 gets hard to read. And over 120 is just insane) Indent! Shows the scope of sections of code. Two, three, or four characters is the usual indentation width Tabs vs spaces? You decide. I prefer spaces. But can you think of an advantage of using tabs instead?
  34. PHP-specific Conventions Zend guidelines http://framework.zend.com/manual/en/coding-standard.html CodeIgnitor guidelines http://codeigniter.com/user_guide/general/styleguide.html PHP Framework

    Interoperability Group (PHP FIG) guidelines for naming classes and files https://github.com/php-fig/fig- standards/blob/master/accepted/PSR-0.md
  35. Automatic Tools for Coding Style phpCodeBeautifier http://www.waterproof.fr/products/phpCodeBeautifier/ A GUI version

    A CLUI version Integrated into PHPEdit A number of configuration options that allow to meet various coding conventions Windows and Linux PHP_CodeSniffer http://pear.php.net/package/PHP_CodeSniffer/ Can detect how well your code conforms to pre-defined coding convention.
  36. Code editing Advanced Text Editors Integrated Development Environments (IDEs) There

    is no reason to use Notepad. It is “like using a teaspoon as a shovel”
  37. Features of advanced editors and IDEs Syntax Highlighting Code completion

    Auto formatting Code templates Code navigation Error and warning highlighting Debugging Integrated Version Control
  38. Example PHP IDEs Commercial PHPEdit Zend Studio Freeware PDT Eclipse

    plugins NetBeans Aptana Studio Dev-PHP (Windows only)
  39. Example Text Editors Commercial TextMate (Mac only) BBEdit (Mac only)

    Freeware Notepad++ (Windows only) TextWrangler (Mac only) Emacs vim gedit Bluefish
  40. Localhost Do not develop directly on the live site You

    might break something on the live site (and you won’t have the chance to test first) The live version of the files becomes the only ones you have Use localhost But try to mirror the live environment as much as possible Use a pre-packaged Apache-MySQL-PHP environment MAMP for Mac EasyPHP or XAMPP for Windows These usually come with essential tools like phpMyAdmin for administering your databases
  41. Introduction to Version Control Version Control is the name given

    to the task of recording changes to a file or set of files so that it is possible to recall specific versions of the file(s) at any point A Version Control System (VCS) is the software used to achieve this task
  42. Introduction to Version Control (cont’d) Many people’s version control consists

    of appending a time or date to the end of a file or directory e.g. index_2012-03-31.php, index_2012-04-25 This approach is error prone and cumbersome (the number of files quickly increases). Also it is difficult to see what the changes are from one version to another.
  43. Introduction to Version Control (cont’d) With a VCS, you can:

    Revert individual files back to a previous state Revert the entire project back to a previous state Compare changes over time See who last modified something that might be causing a problem (useful when working with a team of developers on the same codebase) In general, recover from any potentially serious mistakes
  44. Popular Version Control Systems Bazaar http://bazaar.canonical.com/en/ Darcs http://darcs.net/ Git http://git-scm.com/

    Mercurial http://mercurial.selenic.com/ Perforce http://www.perforce.com/ SVN http://subversion.apache.org/
  45. Git examples – Using GitX client on Mac Figure: Version

    history of code for Simple Blog application
  46. Summary Introduced the topic of Separation of Concerns Introduced MVC

    frameworks as a way of structuring applications to achieve separation of concerns and at the same time enable rapid application development Briefly described some popular PHP libraries Introduced professional best practice (not limited to PHP), including topics such as coding style, development environment, and version control
  47. References The code for the SimpleBlog example was adapted from:

    http://www.symfony-project.org/book/1_0/02-Exploring- Symfony-s-Code http://book.cakephp.org/2.0/en/tutorials-and- examples/blog/blog.html
  48. Further reading . . . on PHP Sebastian Bergmann and

    Stefan Priebsch, Real-World Solutions for Developing High-Quality PHP Frameworks and Applications . . . on General Software Development (Wrox, 2011) Scott, Chacon, Pro Git: Professional Version Control, (Apress, 2009). Available online: http://progit.org/book/ Andrew Hunt and David Thomas, The Pragmatic Programmer (Addison Wesley, 1999) Robert Martin, Clean Code (Prentice Hall, 2008)