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
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
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
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)
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)
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; }
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.
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.
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.
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
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
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
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/
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.
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
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
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’);
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);”
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.”
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
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
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?
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.
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
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
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.
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
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
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)