• Save
Can't Miss Features of PHP 5.3 and 5.4
Upcoming SlideShare
Loading in...5
×
 

Can't Miss Features of PHP 5.3 and 5.4

on

  • 4,589 views

If you're like me you remember the days of PHP3 and PHP4; you remember when PHP5 was released, and how it was touted to change to your life. It's still changing and there are some features of PHP 5.3 ...

If you're like me you remember the days of PHP3 and PHP4; you remember when PHP5 was released, and how it was touted to change to your life. It's still changing and there are some features of PHP 5.3 and new ones coming with PHP 5.4 that will improve your code readability and reusability. Let's look at some touted features such as closures, namespaces, and traits, as well as some features being discussed for future releases.

Statistics

Views

Total Views
4,589
Views on SlideShare
4,584
Embed Views
5

Actions

Likes
12
Downloads
0
Comments
0

1 Embed 5

http://a0.twimg.com 5

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

CC Attribution License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \n
  • \n
  • \n
  • PHP 5.3.0 released June 30, 2009.\nBugfixes and security patches in 5.3.1-5.3.6 (11/2009-3/2011)\n5.3.7 released on Aug. 18, 2011. focused on improving stability\n5.3.8 released shortly after (Aug 23) to fix two issues introduced in .7\n
  • Listed in an ascending level of interesting-ness.\nMagic Constants: LINE, FILE, DIR, FUNCTION, CLASS, METHOD, NAMESPACE\nStandard PHP Library\n
  • \n
  • __DIR__ does not include a trailing space\n
  • Sometimes marginal differences in throughput (execs/sec), but memory consumption is generally lower with respect to dataset size (num elements)\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • This isn’t a terribly intriguing use case, so let’s look at a more practical example.\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Cannot do use(new Obj() as $s) :-(\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Just get over it. Embrace the backslash.\n
  • Organize OO code into self-contained units.\nEver heard of the global namespace pollution issue?\nPEAR naming convention\nImports and aliases.\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Before 5.4 you cannot refer to the object instance that created the closure.\nEXAMPLE\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n

Can't Miss Features of PHP 5.3 and 5.4 Can't Miss Features of PHP 5.3 and 5.4 Presentation Transcript

  • Can’t Miss Features of PHP 5.3 and 5.4Jeff Carouth BCSPHP Sept. 15, 2011 1
  • Hi! I am JeffSenior Developer at Texas A&MAuthor of several magazine articles (php|architect)Infrequent (lazy) blogger at carouth.comLover of progress, innovation, and improvement.Developing with PHP since ~2003 2
  • About you?New to PHP?Using PHP 5.3?Used PHP yesterday? this afternoon? 3
  • PHP 5.3 4
  • What’s all the hubbub?__DIR__SPL improvementsClosures / anonymous functions / lambda functionsNamespaces 5
  • __DIR__“under under durrr” 6
  • __DIR__ usefulness Cleanup autoloading code. That’s about it.include_once dirname(__FILE__) . "/../myfile.php";include_once __DIR__ . "/../myfile.php"; 7
  • SPL ImprovementsSPLFixedArraySPLDoublyLinkedListSPLStack and SPLQueueSPLHeap, SPLMinHeap, SPLMaxHeapSPLPriorityQueue 8
  • We have shiny new datastructures. Use them instead of arrays where appropriate! 9
  • Closures 10
  • The PHP folk are trying to confuse you… 11
  • ...because not allanonymous functions are closures... 12
  • …which aren’t the same as lambda expressions or functors. 13
  • You say semantics? No. There is a difference.(But I’ll step off my soapbox for now. Feel free to ping me later.) 14
  • function() { print Hello;};$myhello = function() { print "Hello!";};$myhello();$myhelloname = function($name) { print "Hello, " . $name . "!";};$myhelloname(BCSPHP); 15
  • function get_closure($name) { $person = new stdclass(); $person->name = $name; return function() use($person) { print "Hello, " . $person->name . "!"; };}$myhelloclosure = get_closure(Gernonimo);$myhelloClosure();// Output: "Hello, Geronimo!" $myhelloclosure is said to “close over” the $person variable which is within its defined scope. 16
  • Using Lambdasarray_walk, array_map, array_reduceusort, uasortarray_filterpreg_replace_callback 17
  • $fabrics= array( array(color => blue), array(color => red), array(color => green), array(color => maroon));usort($fabrics, function($a, $b) { return strcmp($a[color], $b[color]);}); 18
  • // filter based on dynamic criteriadefine(MINUTE, 60);define(HOUR, 3600);define(DAY, 86400);define(WEEK, 604800);$accounts = array( array(id => 1, lastActivity => time()-2*WEEK), array(id => 2, lastActivity => time()-3*DAY), array(id => 3, lastActivity => time()-45*MINUTE), array(id => 4, lastActivity => time()-2*HOUR-5*MINUTE), array(id => 5, lastActivity => time()-5), array(id => 6, lastActivity => time()-3*MINUTE-20), array(id => 7, lastActivity => time()-2*WEEK-3*DAY), array(id => 8, lastActivity => time()-HOUR-33*MINUTE), array(id => 9, lastActivity => time()-5*MINUTE),); 19
  • $results = array();$oneweek = time()-WEEK;foreach ($accounts as $account) { if ($account[lastActivity] > $oneweek) { $results[] = $account; }}$results = array_filter( $accounts, function($account) { return $account[lastActivity] > time()-WEEK; }); 20
  • $getfilterfunc = function($lower, $upper = 0) { $lowerTime = time() - $lower; $upperTime = time() - $upper; return function($account) use($lowerTime, $upperTime) { return $account[lastActivity] >= $lowerTime && $account[lastActivity] <= $upperTime; }}$pastWeekResults = array_filter( $accounts, $getfilterfunc(WEEK));$previousWeekResults = array_filter( $accounts, $getFilterFunc(2*WEEK, WEEK)); 21
  • BOOM!22
  • MOAR PRACTICALCaching.Typically you have a load() and save()method.Perhaps even a load(), start(), and end()method. 23
  • class SimpleCache { private $_data = array(); public function load($key) { if (!array_key_exists($key, $this->_data)) { return false; } return $this->_data[$key]; } public function save($key, $data) { $this->_data[$key] = $data; }}$cache = new SimpleCache();if (($data = $cache->load(‘alltags’)) === false) { $service = new ExpensiveLookupClass(); $data = $service->findAllTags(); $cache->save(‘alltags’, $data);} 24
  • class SimpleCacheWithClosures { protected $_data = array(); public function load($key, $callback) { if (!array_key_exists($key, $this->_data)) { $this->_data[$key] = $callback(); } return $this->_data[$key]; }}$cache = new SimpleCacheWithClosures();$service = new ExpensiveLookupClass();$data = $cache->load(alltags, function() use($service) { return $service->findAllTags();}); 25
  • FunctorsBecause the rest just wasn’t enough… 26
  • Functors, in simple terms,are objects that you can call as if they are functions. 27
  • class Send { private function _broadcast() { return Message sent.; } public function __invoke() { return $this->_broadcast(); }}$send = new Send();debug_log($send()); 28
  • NamespacesAll the cool languages have them.or perhaps PHP just wants to be JAVAwith all its package gloryafter all, we do have PHARs 29
  • Nope. Namespaces solve a real need. 30
  • The “” Separator 31
  • Namespace BenefitsOrganization. Both file and code.Reduce conflicts with other libraries.Shorten class names.Readability. 32
  • define("LIBRARYDIR", __DIR__);class Tamu_Cas_Adapter { function auth() { }}function tamu_cas_create_client() { return new Tamu_Http_Client();}namespace TamuCas;use TamuHttpClient as HttpClient;const LIBRARYDIR = __DIR__;class Adapter { function auth() { }}function create_client() { return new HttpClient();} 33
  • Namespace organizationIn /path/to/Tamu.php:namespace Tamu;In /path/to/Tamu/Dmc.phpnamespace TamuDmc;In /path/to/Tamu/Auth/Adapter/Cas.phpnamespace TamuAuthAdapter;class Cas { } 34
  • Conflict Resolutionnamespace My;function str_split($string, $split_len = 2) { return "Nope. I dont like to split strings.";}$splitstr = str_split(The quick brown fox);// $splitstr = "Nope. I dont like to split strings."$splitstr = str_split(The quick brown fox);// $splitstr = array(T, h, e, ..., o, x); 35
  • Class name shorteningclass Zend_Application_Resource_Cachemanager extends Zend_Application_Resource_ResourceAbstract{ //...}namespace ZendApplicationResource;class Cachemanager extends ResourceAbstract{ //...} 36
  • Readability by Namespacerequire_once "Zend/Http/Client.php";$client = new Zend_Http_Client();use ZendHttp;$client = new Client();use ZendHttpClient as HttpClient;$httpClient = new HttpClient(); 37
  • Take a deep breath 38
  • PHP 5.4alpha3 was used for demosbeta going to be packaged on Sep 14(source:php-internals) 39
  • New FeaturesClosures support $this keywordShort Array SyntaxArray DereferencingTraits(Debug webserver) 40
  • Closures and $thisclass HelloWorldPrinter{ public function __construct($name) { $this->_name = $name; } public function getPrinter() { return function() { return "Hello, " . $this->_name . "!"; }; }}$instance = new HelloWorldPrinter(BCSPHP);$printer = $instance->getPrinter();echo $printer(); 41
  • Prior to PHP 5.4Fatal error: Using $this when not in object context in /Users/jcarouth/Documents/code-bcsphp-092011/php54closurethis.php on line 14PHP 5.4.0alpha3 (built Aug 5, 2011)Hello, BCSPHP! 42
  • Short Array Syntax Saving you a few keystrokesand compute cycles when switching from JavaScript 43
  • Really, who doesn’t loveJavaScript array syntax? 44
  • //empty array$arr = [];//simple array$arr = [1, 2, 3];//"dictionary" array$arr = [name => jeff, language => php];//multi-dimensional$arr = [[orange, blue], [black, gold]]; 45
  • Array Dereferencing 46
  • $array = array(1, 2, 3);$dereference = *$array; Sorry, no pointers. All the upset C++ wizards, go have some pizza. 47
  • class UserDataSource{ public function getDataForJeff() { return [ id => 1, name => Jeff Carouth, isAdmin => true, ]; }}$jeff = $store->getDataForJeff();if ($jeff[isAdmin] === true) { //give him access to all the things} PHP <= 5.3if ($store->getDataForJeff()[isAdmin]) { //shorter...but be mindful} 48 PHP >= 5.4
  • PitfallsDereferencing a non-existent key produces aNOTICE.If the function does not return an array,unexpected behavior. 49
  • Traits! 50
  • DefinitionTraits is a mechanism for code reuse in singleinheritance languages such as PHP. A Trait isintended to reduce some limitations of singleinheritance by enabling a developer to reusesets of methods freely in several independentclasses living in different class hierarchies. Thesemantics of the combination of Traits andclasses is defined in a way, which reducescomplexity and avoids the typical problemsassociated with multiple inheritance and Mixins. 51
  • A bit much to take inThe important bit is traitsallow developers like you toincrease code reuse and getaround limitations of single-inheritance. 52
  • Show me the code!trait Named { function name() { //function body }} 53
  • class SearchController { public function findBook(Book $b) { } private function log($message) { error_log($message); }}class AdminController { public function grant(User $u, Privilege $p) { } private function log($message) { error_log($message); }} 54
  • trait Logging { private function log($message) { error_log($message); }}class SearchController { use Logging;}class AdminController { use Logging;} 55
  • namespace TamuTimesModels;class Story { public function setDataStore($store) { $this->_ds = $store; } public function getDataStore() { return $this->_ds; }}class User { public function setDataStore($store) { $this->_ds = $store; } public function getDataStore() { return $this->_ds; }} 56
  • namespace TamuDmcApp;trait DataStore { public function setDataStore($store) { $this->_ds = $store; } public function getDataStore() { return $this->_ds; }}namespace TamuTimesModels;use TamuDmcAppDataStore;class Story { use DataStore;}class User { use DataStore;} 57
  • namespace BCSPHP;trait MessageBroadcast { public function sendMessage() { } abstract private function _formatMessage();}class MeetingNotification { use MessageBroadcast; private function _formatMessage() { return "Notice: BCSPHP Meeting " . $this->_date; }} 58
  • Traits are “just compilerassisted copy and paste.” - Stefan Marr, PHP Internals Mailing List, Nov 2010 59
  • Built-in Development Server 60
  • DEMOphp -S 0.0.0.0:8080 -t /path/to/docroot 61
  • Caveat Routing must be handled with a separate router.php script.if (file_exists(__DIR__ . / . $_SERVER[REQUEST_URI])) { return false; // serve the requested resource as-is.} else { include_once index.php;}if (php_sapi_name() == cli-server) { /* route static assets and return false */} 62
  • What you can do now:(more like what you should do)Test PHP 5.4 — http://qa.php.netRun make testTEST YOUR APPS against PHP 5.4-alpha/beta/RC 63
  • That’s all folks!QUESTIONS?@jcarouthjcarouth@gmail.comjeffcarouth.info 64
  • Have feedback?http://joind.in/3716 65
  • ResourcesEnygma’s PHP 5.3 example codehttp://bit.ly/q9Eu36Elazar’s benchmarks of SPL features in PHP 5.3http://bit.ly/nKsbvQPHP documentation on the built-in web serverhttp://bit.ly/rc26l0 66