2015年6月19日星期五

Site News: Popular Posts for the Week of 06.19.2015

Popular posts from PHPDeveloper.org for the past week:

Loosely Coupled Podcast: Episode 24: Minimum Viable Product


The Loosely Coupled podcast, with hosts and PHP community members Jeff Carouth and Matt Frost, has posted their latest episode today - episode #24: Minimum Viable Product.



In this episode Jeff and Matt talk about the concept of a minimum viable product and what it means to us as developers. The concept of an MVP is simple but it often gets used as an excuse to put out poorly-implemented products. Listen as Jeff and Matt discuss their opinions about the problems with MVP in our industry and how we as developers can fight against them.


You can listen to this latest episode either through the in-page audio player, by downloading the mp3 or by subscribing to their feed to get this and other episodes as they're released.


Link: http://looselycoupled.info/blog/2015/06/18/episode-24-minimum-viable-product/

HHVM Blog: Trait and interface requirements in Hack


On the HHVM blog there's a recent post looking at some of the requirements around traits and interfaces in the Hack language. More specifically, they talk about type checking with traits and how interfaces can be used to help provide extra structure.



In PHP, traits are a mechanism of code reuse that, while very powerful, are also difficult to type check both efficiently and exhaustively. In this post we'll dive more deeply into the reasons for that and see how Hack solves those problems, allowing you to use traits in a safe way without limiting their expressiveness.


They start by talking about the main problem with PHP's handling of traits (essentially copy and paste into the current class) and how they felt Hack should "just work" in allowing type checking on these "pasted" methods too. Performance limitations prevented them from handling it how they do with other variable types, so they changed things up, using a "require extends" syntax to tell the Hack engine how to allow the checking based on an interface. There's a lot more to it than this, so be sure to read the rest of the post on how they came to that conclusion.


Link: http://hhvm.com/blog/9581/trait-and-interface-requirements-in-hack

NetTuts.com: Programming With Yii2: Rich Text Input With Redactor


NetTuts.com continues their series about programming with the Yii2 framework in this new article moving on to the use of the Redactor rich text editor that comes bundled with the framework.



In this Programming With Yii2 series, I'm guiding readers in use of the newly upgraded Yii2 Framework for PHP. In this tutorial, I'm going to introduce you to using the rich text editor Redactor within the Yii Framework. For these examples, we'll continue to imagine we're building a framework for posting simple status updates, e.g. our own mini-Twitter.


Thanks to the Yii community purchasing an unlimited license for the Redactor rich text editor, it's easy to install and use via the "yii2-redactor" extension. They help you get it installed and update a sample form to use it instead of the normal basic HTML textarea for content input. They also show you how to add image support and what it looks like both inline in the editor and the resulting HTML output.


Link: http://code.tutsplus.com/tutorials/programming-with-yii2-rich-text-input-with-redactor--cms-23174

Run Geek Radio: Episode 005 - Time Estimation, Conference Talk Rating, Contest Winner


The Run Geek Radio podcast has posted their latest episode today. In it (episode #5) host Adam Culp talks about time estimation, thoughts on conference talk ratings and the contest winner from his standing desk contest mentioned in an earlier episode.



This episode Adam Culp announces the winner, David Stockton (Colorado), of the contest launched in Run Geek Radio episode 004. [...] Adam also talks briefly to clarify his views on "soft talks" versus "soft skills talks", and how he was misrepresented as disliking soft skills talks though the opposite is true. [...] Then this episode is rounded out with a detailed coverage of time estimation in relation to projects, and why it is so vitally important to be accurate. Adam also speaks about how important proper requirements gathering is to the process.


You can either use the in-page audio player to listen to this latest episode or you can download the mp3 of the show. Be sure to subscribe to the feed if you enjoy the show and want to hear more from Adam.


Link: https://rungeekradio.com/episode-005-time-estimation/

Giorgio Sironi: Property-based testing primer


Giorgio Sironi has a new post to his site today talking about a method (and tool) around a different sort of testing practice: property-based testing. The difference is that, instead of hard-coding values and evaluating them post-processing, you're generating random values and ensuring they match against a set of properties, not values.



I'm a great advocate of automated testing and of finding out your code does not work on your machine, 30 seconds after having written it, instead of in production after it has caused a monetary loss and some repair work to be performed. [...] However, classic test suites written with xUnit and BDD styles have some scaling problems they hit when you want to exercise more than some happy paths. [...] Property-based testing is an approach to testing coming from the functional programming world.


He helps to make the point a bit more clear with an example of testing the "sort" function and its results. He talks about how to test it using normal data, empty data, etc. but notes that this kind of testing can become "boring and error-prone". Instead he proposes the property-based testing of the results. He generates random values to feed into the method and checks to ensure the results are sorting by comparing them to each other. He expands this with a bit more complex example, showing how to test some DateTime handling and evaluating the result with logic in a closure. To help make this kind of testing easier, he's created a library (Eris) that extends PHPUnit and provides the methods seen in his examples.


Link: http://www.giorgiosironi.com/2015/06/property-based-testing-primer.html

Sammy Powers: Contributing to the PHP Manual


If you've wanted to contribute something back to PHP but aren't familiar with C (or don't feel comfortable enough with it) Sammy Powers offers another solution. In his latest post he shows you how to contribute to the PHP documentation and update the manual for new features, missing information or fixes to current code examples.



If you've been wanting to contribute to PHP internals, starting with the documentation can be a great entry point; especially because it doesn't require dusting off those old C books from college. But knowing where to start can be tricky since information on how to contribute to the docs is scattered across the internet. This article is a step-by-step guide of how to contribute documentation to the PHP manual.


He starts with the "quick and dirty" way of editing the manual through the edit.php.net site, but points out that it's really only useful for smaller changes, not large documentation updates. The rest of the post shows you how to set up the documentation locally and generate the results to validate your changes. He talks some about the DocBook format they're written in, the build process with the PhD (PHP docs generator) and running the php.net test suite against the changes. This ensures that nothing else has broken on the site in the process.



He shows you where to make your changes, how to generate it from either a skeleton or using the docgen script and submitting the changes back to the repository. There's also a few other random changes to make before committing the files back via SVN and pushing them back upstream. He ends the post talking about the GoPHP7-ext project and how to find extensions that are missing documentation or where it's incomplete (easy thanks to an included "check-missing-docs" file included in the repository).


Link: https://www.sammyk.me/how-to-contribute-to-php-documentation

2015年6月18日星期四

Site News: Blast from the Past - One Year Ago in PHP

Here's what was popular in the PHP community one year ago today:

Scotch.io: Deploy PHP Apps Easily with Laravel Forge


The Scotch.io site has a new post that wants to help make your Laravel deployments on Forge a simple thing. Forge is a "frontend" to make deployment on the hosting platform of your choice simpler with features for configuring the server, application deployment and automation (like push to deploy).



Forge is an incredible tool in the family of Laravel products that helps developers focus on developing, not deploying and hosting. I personally use it when deploying Laravel applications and it does make life much easier. Many of the pain points of hosting are taken care of for you so you can get right back to developing. [...] We'll be diving into how we can deploy a Laravel application to Forge using Digital Ocean and GitHub.


He starts with a brief introduction to how Forge works and cooperates with the Digital Ocean stack to create the server and deploy the application. He answers a few questions about "why should you use Forge" and then gets into the actual setup of the server. He walks you through:



  • Linking the project to a GitHub or BitBucket repository
  • Adding SSH keys to connect to use for connecting to the server
  • Creating a server


He also goes through some of the server management features Forge offers in its dashboard including monitoring services, server tools and basic site management controls. Once everything is set up, he shows how to deploy from the GitHub repository and how to use third-party integrations (like Slack or HipChat) and the use of environment variables.


Link: https://scotch.io/tutorials/deploy-php-apps-easily-with-laravel-forge

MyTechBuilder.com: Optional Value Control-flows in PHP using Traits and Magic-methods


The MyBuilderTech.com site has a new tutorial posted talking about the use of traits and magic methods for optional value handling.



Recently I have been interested in experimenting with different ways to handle optional values. Their are many examples that exist demonstrating the use of the Maybe/Optional structure within the PHP landscape. I would instead like to focus my attention on only looking into the concept of 'orElse', which I have found to be a prominent control-flow whilst using these types of value. Typically, in an imperative mind-set we are accustom to evaluating a value, and based on its existence - defined as falsely in this regard - follow a different course of action, and by-way result.


He gives an example of where a value is checked for null and something else happens when it is. This is a common practice in PHP development, but he's more interested in other ways of handling. The first of these ways is with traits. His example shows an "OrElse" trait that can be used to perform the same evaluation but does some extra magic based on the method name called (his example is "findByIdOrElse"). If the trait method isn't for you, he also offers another possible solution around the use of composition. In this case he uses the same trait but makes it a part of its own class that's then given the object to work with (his "repository").



The post ends with one more "bonus" method for handling optional values - a simple function ("_or") that evaluates the arguments given and returns the first that's "truthy".


Link: http://tech.mybuilder.com/optional-value-control-flows-in-php-using-traits-and-magic-methods/

Ben Ramsey: Composer: Missing Distributions for Explicit References


Ben Ramsey has shared an interesting issue he's come across when installing packages via Composer where it installed a different version than expected when he ran an install. The problem turned out to be from an unexpected place.




For applications I control that are not distributed to the public, I like to hard-lock my Composer dependencies to a specific version. [...] Sometimes a library has updates that haven't yet been released, and I need to use these right away. Composer allows me to specify the specific commit I want to use for a library. In this way, I can hard-lock a dependency to a specific state, even when there is not yet a release for the changes I need. This has worked well until today, when I tried to do a fresh composer install. After installing, one library contained files and methods that I did not expect. It turns out Composer was grabbing the HEAD of dev-master instead of the specific commit I referenced.




After some investigation into his "composer.lock" file's contents, he found the issue: a problem with the way that BitBucket handles the distribution zip files Composer requests. In his example, the zip file was of the HEAD on the repository, not of the specific commit (GitHub doesn't have this problem). His solution was using the (slower) "--prefer-source" option to grab the correct commit contents...not an ideal solution but it does what he needs.


Link: http://benramsey.com/blog/2015/06/composer-missing-distributions/

SitePoint PHP Blog: Popular Users per Language and Region with Silex and Github


The SitePoint PHP blog has a new tutorial posted showing you how to use the data the GitHub API provides to find popular users, per language, in an area. His sample example is a simple Silex framework based application and uses the KNPLabs GitHub library to interface with the API.



The data you can get through the GitHub API V3 is mostly what you can see on the GitHub web interface, except you can use the data in your application to come to interesting conclusions. That is what we are going to do in this article. [...] Now, what if there was a web service in which we could specify a location and a language (e.g. PHP) and get a sorted list of contributors to open-source? [...] In our web service, we will have one endpoint (i.e. action, URL) that shows the most popular ten creators. The most popular creators are the people in a location who have the largest number of stargazers. For this, we will retrieve each person's repositories and add up the number of times each one has been starred.


He steps you through getting a Homestead Improved VM up and running (via Vagrant) and a basic Silex application up and running inside. He then pulls in the KNPLabs GitHub library via Composer and sets up a new client in the default route (and grabs the public user data for a user). He then shows how to change it up and use the Search API and some special queries to locate users by a given location. He adds another class, a "StarGazerCalculator", that's given the users returned, filters out the forks in the list and calculates the total "stargazer" count for the user. He does the same with the "top creators" list and sets it up as a service provider, fetches the data and returns the results as a JSON document.


Link: http://www.sitepoint.com/popular-users-per-language-region-silex-github/

Community News: php[world] 2015 Schedule Announced


The next php[world] conference is coming up in November of this year and they've just announced the full schedule for their 2015 event.



In keeping with the cross-community theme, they've gathered speakers from the general PHP, WordPress, Drupal, Joomla, Zend Framework, Symfony and CakePHP communities together in one place. Sessions at this year's event include:



  • "HTTPS is Coming: Are You Prepared?"
  • "Test, Create, Secure, Repeat"
  • "Scrummy Bums: Adventures in Agile Process"
  • "Using Lessons Learned to Create Web-Manageable Symfony Apps"
  • "Invented Here: Migrating Legacy Data to Drupal 8"
  • "Magento 2 Dependency Injection, Interceptors, and You"
  • "Dev Divas: Amazing Women Who Shaped Computer Tech"


There's also keynotes from well known community members Andrew Nacin, Tessa Mero, Lorna Mitchell and Taylor Otwell. You can see the full lineup here and, if you want to pick up tickets of your own, you can do it directly from the site.


Link: https://world.phparch.com/schedule/

2015年6月17日星期三

Community News: Recent posts from PHP Quickfix

Recent posts from the PHP Quickfix site:

Three Devs & A Maybe: Episode 68 - Podcasting, Remote Working and Testing with Adam Wathan


The Three Devs & A Maybe podcast has released their latest episode today, Episode #68 - Podcasting, Remote Working and Testing with Adam Wathan.



This week we are very lucky to be joined by fellow podcaster and host of Full Stack Radio - Adam Wathan. We begin discussion with his reasons behind starting a podcast, experience being a solo-host and the secret to great podcast recordings. We then move on to how he got into programming at high school - with reflection on that if he had been using a Windows machine at college, he would most likely be a .NET developer by now. As both Edd and Adam work remotely at this time, the topic of remote pair-programming and Kanban style board implementations then arises. Finally, we discuss his thoughts on Message-passing vs. strict-contracts, Smalltalk and Elixir exploration and how it is hard to give a definitive answer on the best way to begin learning TDD.


You can listen to this latest episode either through the in-page audio player or by downloading the mp3. Be sure to subscribe to their feed if you enjoy the show too!


Link: http://threedevsandamaybe.com/podcasting-remote-working-and-testing-with-adam-wathan/

Stephan Hochdörfer: Simple Logging Facade for PSR-3 loggers


In his latest post Stephan Hochdörfer shares a library he's created to hopefully make it easier for developers to integrate PSR-3 compatible logging libraries into their code, a "logging facade" based on an idea from the Java world.




Lately I have seen more and more libraries picking up PSR-3 when it comes to logging. What a lot of libaries do wrong is that they depend on a concrete implementation of PSR-3, e.g. Mongolog instead of relying on the PSR-3 interface. From what I have seen this is because loggers get instantiated directly within the class. This is not a bad thing but it couples your code to a concrete implementation of PSR-3 which in turn means that there`s no interoperability.



The Java community solved the problem by creating a Simple Logging Facade library (SLF4) which I "ported" to PHP last week.




The library makes provides a simple static interface to setting the PSR-3 logger of your choice and fetching it from anywhere in your application. He includes an example of what the code would look like for a basic Monolog instance. He ends the post talking about this method for getting/setting the logger instance and how it compares to using other options like a dependency injection container or even just a manual call to a setter.


Link: https://blog.bitexpert.de/blog/simple-logging-facade-for-psr-3-loggers/

Laravelista.com: Build an API with Lumen and Fractal


On the Laravelista.com site there's a recent tutorial posted showing you how to create an API with Lumen and Fractal, a combination of the popular Laravel-based microframework and Fractal, an output handling library that makes it simpler to transform data to your needs. This is the second part of his series (part one is here), making some improvements on his previous examples.



In the previous post I used Larasponse to get Fractal working with Laravel, but recently I have switched to native Fractal package. One thing to notice is that in this post I will be showing you parts of code from a real project that I am working on called Treeline, instead of just example code like in the previous post. Be sure to check the Treeline repository if you're unclear on something.


He goes back through some of the setup process, getting Fractal installed via Composer and the creation of an ApiController to handle basic things like setting the status code and transforming the response to JSON. He shows how to add in the necessary routes for the "projects" path and creates the matching controller, collection and item classes that integrate the Fractal transformers to format their output as JSON. He also includes the code for the transformer classes themselves, showing you how to pull in and modify the data for the API's needs. He ends the post showing how to integrate other data (the "notes" into a "project" instance) and the resulting JSON output.


Link: http://laravelista.com/build-an-api-with-lumen-and-fractal/

Community News: PHPPackages.org


A new community resource, built on top of the excellent Composer and Packagist technology that's popular in today's PHP development world, has been released and provides more context about libraries and provides a "rank" for each one - PHPPackages.org.



PHPPackages.org was built to solve the following problems: [it] defines popularity rank for php packages, provide a space for discussion and [helps to] discover which packages use a specific package.


The About page has more information about the site, how they calculate the "popularity" metric, what the various icons mean and what kinds of things you can do on the site. It's a great resource, especially for those wondering who is using their packages and to discover new packages that are more widely used. It has a lot of the same information that the Packagist site contains but that little extra bit of data is quite useful.


Link: https://phppackages.org/

Paragon Initiative: Everything [About] Preventing Cross-Site Scripting Vulnerabilities in PHP


The Paragon Initiative has posted a new tutorial that wants to provide you with everything you need to know about preventing cross-site scripting in PHP applications.




Cross-Site Scripting (abbreviated as XSS) is a class of security vulnerability whereby an attacker manages to use a website to deliver a potentially malicious JavaScript payload to an end user. XSS vulnerabilities are very common in web applications. They're a special case of code injection attack; except where SQL injection, local/remote file inclusion, and OS command injection target the server, XSS exclusively targets the users of a website.



[...] Cross-Site Scripting represents an asymmetric in the security landscape. They're incredibly easy for attackers to exploit, but XSS mitigation can become a rabbit hole of complexity depending on your project's requirements.




He introduces the concept of cross-site scripting (XSS) for those new to the term and provides a brief "mitigation guide" for those wanting to jump to the end. He then gets into some examples of what a XSS vulnerability could look like, both stored and reflected and provides the "quick and dirty" method for preventing them. He also mentions some tips in implementing your solution including avoiding HTML in your data if at all possible. He goes on to talk about the use of HTMLPurifier to prevent attacks, context-sensitive escaping (HTML vs JS vs CSS) and some of the browser-level features that help prevent XSS for the user.


Link: https://paragonie.com/blog/2015/06/preventing-xss-vulnerabilities-in-php-everything-you-need-know

2015年6月16日星期二

Community News: Latest PECL Releases for 06.16.2015

Latest PECL Releases:
  • timezonedb 2015.5
    Updated to version 2015.5 (2015e)


  • wxwidgets 3.0.2.0
    * Updated the thread.php example to work properly.
    * Remove delete on the wxThread garbage collector function, which
    should fix most issues on #84.
    * Modified wxWindow::GetHandle to return the XWindowID on Gtk which
    should really fix #86.
    * Enabled wxWindow::GetHandle by casting WXWidget to size_t.
    * Enabled wxOutputStream::Write and wxInputStream::Read variations
    that take a 'void* buf' as argument which should fix issue #87
    * Updated version numbers and added userland version constants:
    WXWIDGETS_LIBRARY_VERSION and WXWIDGETS_EXTENSION_VERSION.
    * Added --with-wxwidgets-version to package.xml so 'pecl install
    wxwidgets' can ask for a different version of wxWidgets library to
    download and compile.
    * Set the default wxWidgets version to download and compile on linux
    and mac to 3.0.2. Also added a new configure option
    --with-wxwidgets-version to explicitly change the version of
    wxWidgets to download, eg: --with-wxwidgets-version=3.0.1
    * Forgot to conditionally fetch tsrm on wxAppWrapper.
    * Fetch TSRM on wxAppWrapper which probably fixes issue #70
    * Unmodified copy of wxImage::GetData to zval which fixes #75.
    * Own the data parameter on wxImage SetData to really fix issue #75.
    * Custom templates for wxImage GetData and SetData which fix
    and close #75.
    * Updating location of Mac OS X SDK in docs (chrisnharvey).
    * Updating docs for building on Mac OS X (chrisnharvey)
    * Updating link to heading
    * Updating macosx-version-min to 10.9
    * Added sdl, sdl_sound as dependencies on archlinux PKGBUILD.
    * Updated config.m4 to require sdl and sdl_sound on linux which
    fixes #2.
    * Removed some testing printf code.
    * Added some wxApp methods.
    * Fix to correctly brake search for wx-config when first found in
    config.m4 file.
    * Added wxPHP shell script in /usr/bin/wxphp.
    * Added some wxApp methods.
    * Automated Mac OSX detection which should fix #94.
    * Simplified README.md and added building steps into INSTALL.md.
    * Removed trace of debugging code.
    * Merge child class method overrides that differ into parent methods
    which should fix #97.
    * Added drag and drop example.
    * Disabled pointer deletion for wxDropTarget and child classes
    to fix segmentation fault which fixes #98.


  • mongo 1.6.9
    ** Bug
    * [PHP-1426] - Ensure buffer lengths are checked in bson_to_zval()
    * [PHP-1448] - Ensure DBPointer namespace length reads as little-endian
    * [PHP-1450] - Ensure strings are null-terminated in bson_to_zval()
    * [PHP-1453] - Ensure BSON buffer is checked before reading regex pattern/flags

    ** Improvement
    * [PHP-1449] - Ensure value is freed when bson_to_zval() encounters an error
    * [PHP-1452] - bson_decode() should require exactly one document in buffer


  • pq 0.6.0RC1
    * Fixed crash with result iterator when the iterator exists longer than the result
    * Fixed array parser compatibility with arrays of boxes
    * Added pqStatement::deallocate{,Async}() and pqStatement::prepare{,Async}() methods
    * Added pqStatement::$query and pqStatement::$types readonly properties
    * Added pqCursor::{open,close}Async() methods
    * Added pqCursor::$query and pqCursor::$flags readonly properties


SitePoint PHP Blog: Boxing up your Apps as Phars Quickly and Easily with Box


The SitePoint PHP blog has a new tutorial posted showing you how to easily package up your application with Box to make phar files without the extra hassle of building them yourself.



In this tutorial, we'll use Box to package a PHP application into a Phar, in order to make it easily distributable and globally installable via Composer.


For his example he uses the PHP portion of the FolderBuilder project and makes a command-line executable that can return the information for a directory as JSON data. He starts by installing the "box" executable command on a local VM and defines the simple configuration file, a "box.json" with some basic settings. He then clones the FolderBuilder project, updates the configuration for the correct locations and files and executes the "build" command. The result is a phar file that contains the PHP script functionality. He also updates the configuration to make the result executable with a "chmod" setting, removing the need to call it with the PHP command line version. He ends the post showing how to test it out, taking the results and dropping them into FolderBuilder to make sure they're 100% correct.


Link: http://www.sitepoint.com/boxing-apps-phars-quickly-easily-box/

Voices of the ElePHPant: Interview with Matthew Weier O'Phinney


The Voices of the ElePHPant podcast has posted their latest episode interviewing a member of the PHP community. This time host Cal Evans talks with Matthew Weier O'Phinney of the Zend Framework team.



In this new episode Cal and Matthew talk about a conversation they were involved in about Conduit, a "middleware for PHP" project. It came from some of his testing with Node.js and wondering why PHP didn't have something similar. This lead to the PSR-7 proposal from the PHP-FIG group with a standardized HTTP request and response structure. They also talk about how these concepts are being integrated into frameworks like Zend Framework and how it's helping improve performance. They also talk about how this move will effect major projects like WordPress or Drupal. They wrap things up talking about Zend Framework v3 and the work that's currently being done to split up the components and lock down the framework as a "meta-package" with specific versions of the components.



You can listen to this latest episode either through the in-page audio player or by downloading the mp3 for listening at your leisure. If you enjoy the show, be sure to subscribe to their feed to get this and future episodes as they're released.


Link: https://voicesoftheelephpant.com/2015/06/16/interview-with-matthew-weier-ophinney-3/

Loïc Chardonne: Symfony Differently - part 2: Bootstrap


Loïc Chardonne has posted the latest part in his "Symfony Differently" series (part one is here) with a focus on bootstrapping the application and configuring the environment that it will live in.



Our goal in this post is to bootstrap an application to then create a search endpoint for items. We've decided to use Symfony for a single reason: our company Acme used it since the beginning and the API developers team has Symfony and PHP skills.

He walks through the steps you'll need to get the application up and running:



  • Creating a new Symfony Standard Edition project
  • Configuring Apache
  • Moving the tests to a different directory, including Composer updates
  • Creating scripts for builds, testing and deployment


With all this structure in place, the next part of the series will start in on the functionality of the search endpoint and returning the results.


Link: http://gnugat.github.io/2015/06/10/sf-differently-part-2-bootstrap.html

Community News: Packagist.org Gets a Makeover


If you're a Composer user by now you've noticed a major overhaul that's happened to the Packagist.org website in the last few days. They've made a major improvement to how the site looks and have added some fun new functionality to help make finding packages easier.


According to the Laravel News site, updates include a change in the recommended install method, the addition of more GitHub metadata and the inclusion of the project's README file. The site will also allow you to sort (ascending and descending) by the number of stars the repository has as well as the number of downloads.



The site still includes all of the information it dod before too including version listings, details about what the package requires, license information and links to more information and the actual repository. Check out the new look and see what you think. Packagist is also an Open Source project so if you find an issue, be sure to either report it to the project or get in, fix it yourself and make the pull request to submit it.


Link: http://packagist.org

Loosely Coupled Podcast: Episode 22: Resolution Won't Fix


The most recent episode of the Loosely Coupled podcast, with hosts and PHP community members Jeff Carouth and Matt Frost, has been posted: Episode #22 - Resolution Won't Fix.



In this episode Jeff and Matt talk about a very important skill all developers need to learn: how to say no. Saying no is pretty easy but there are ways to appropriately convey the reason why doing what is being asked is not a good idea.


You can listen to this latest episode either using the in-page audio player, by downloading the episode or you can subscribe to their feed to get the latest as they're released. Also, be sure to follow them on Twitter too!


Link: http://looselycoupled.info/blog/2015/06/13/episode-22-resolution-wont-fix/

Mind the gap

Are your users falling between the gaps? The gaps between devices, channels and business units.

Things used to be so simple. Customers would pass through a standardised sales funnel that would end with them making a purchase. Even when the web started to disrupt this sales funnel things were still pretty simple. Your corporate website would just about fit into that funnel.


But things have become more complex. The traditional sales funnel no longer applies. User journeys are becoming more convoluted, especially in light of device switching.


Gaps between devices


Research by Google seems to show that 90% of users switch between devices during a transaction online. It is unsurprising that prominent figures in web design are talking about device switching. They are highlighting the dangers of users becoming confused. That as users switch between devices they become less likely to buy. It is a legitimate concern and as user interface designers these are problems we need to address.


Google research shows us that users switch between devices.
Google research shows us that users switch between devices.

But these are not the only gaps that exist in the user journey of todays connected consumers. There is also gaps between channels.


Gaps between channels


Users don’t just switch between devices. They switch between channels too. That might be moving from Facebook to your website or from a blog to Twitter. But it could just as easily switching between online and a call centre. Like switching between devices these can be points of weakness. Points where the user could become confused or receive an inconsistent experience.


That is why I like the Barclays Banking Mobile App so much. If I have logged into the mobile app and then need to speak to a person, I am not required to verify my identity again. They have made the transition painless.


Companies like Barclays Bank are focusing on the gaps between channels.
Companies like Barclays Bank are focusing on the gaps between channels.

Yet so many other organisations fail to consider these transition points. For example the transition between website and social media is often poor. As I have written before, things could be much better.


But gaps do not just exist at transition points. They also happen over time.


Gaps in time


The National sales executive association say that 80% of sales happen on the fifth to twelfth contact. In other words often users are not going to act on their first visit to your website. They may well return many times. What happens in those gaps is crucial for deciding whether a sale happens. Are you following up on those who got half way through a registration process before abandoning? Do you reach out to those who liked one of your pages on Facebook?


But more than that, are you making it easy for them to pick up where they left off? Does your website remember login details or site settings? Are they expected to re-enter half completed forms when they come back to your site later? Putting thought into how to nurture the user relationship over time is a crucial component of digital design.


We cannot solve all ‘gap problems’ with good design and well built applications. Some are organisational in nature.


Organisational gaps


It is easy to focus on the design and technology problems we can fix and use them as an excuse to ignore the elephant in the room. You see when it comes to users falling between the gaps the biggest gap is between business silos.


Many organisations manage customers using a waterfall approach. Marketing cultivates the leads. Sales are then responsible for converting those leads. Production delivers the product or service, before customer service handles post sales support. Unfortunately the transition points between these silos can be a disjointed experience for customers.


Take for example one client I worked with who had different targets for the marketing and sales department. Marketing had to generate a certain number of leads in a year while sales had to convert a percentage of these.


Marketing didn’t care about the quality of leads. So they insisted users could only see their product demo once they had handed over their email address. Of course many users didn’t wish to get a call from a sales man. At least not yet. This wasted both the sales departments time and angered many potential customers.


Another example of users falling between the gaps occurred when I purchased an iPad. I couldn’t enable the personal hotspot on it so I went to my network providers website to see if there was a fix. When I failed to find an answer I called their call centre. After sitting on hold for over 30 minutes customer support informed me it was Apple’s problem.


In the end I posted by frustration on Twitter. Within ten minutes somebody from my carriers social media team contacted me saying it was a known problem and provided a fix.


The problem was clear. The marketing department (who ran the social media channels) hadn’t communicated. They hadn’t told either the web team or the customer service department about the fix. As a result I had fallen through the gaps.


The user experience delusion


Users have come to expect outstanding user experience. It is becoming the key differentiator for companies across a wide range of sectors. Yet many companies are in denial about how well they are doing. They cannot see the gaps in the experience.


In his TIME article ‘Customer Service Hell’ Brad Tuttle explained that 80% of companies believed they offered a superior customer service. Yet only 8% of their customers agreed. Offering a great customer experience is about the details and those details happen in the gaps. The gaps between devices, channels, business silos and over time. It is our job as user experience specialists to highlight these issues and help address them.








2015年6月15日星期一

Community News: Latest PEAR Releases for 06.15.2015

Latest PEAR Releases:

SitePoint PHP Blog: Exploring Github's Public Events with PHP and Google BigQuery


The SitePoint PHP blog has a new tutorial posted showing you how to explore GitHubs public events through the GitHub API and handled via the Google BigQuery infrastructure taking the burden off your own systems.



If you've been following along with my previous articles about Github's API, you know that Github's developers are doing their best to ease the pain of interacting with Github data. In this article, we're going to take a look at the Github public events API and we will build a small demo along the way.


They start off with a brief introduction to both GiHub events (like pushes, merges, etc) and the BigQuery system and the problem it solves. They use a stock Laravel framework-based application (on a Homestead Improved VM) and add in the Google API credentials and a BigQueryServiceProvider using Google's own client to make the connection. They also set up a middleware authentication mechanism to redirect the user if they're not authenticated. They then move over to the BigQuery side and show how to use it's web-based console to perform queries and view results. They then translate this over to a simple "top ten" query, listing the top repositories ordered by number of forks. Building on this, they add in a simple form that allows the user to specify the language to search for (PHP, Javascript, etc) and outputs the results via a Blade template.


Link: http://www.sitepoint.com/exploring-githubs-public-events-php-google-bigquery/

PHP.net: Release of PHP 5.4.42, 5.6.10 & 5.5.26


The PHP.net site has announced the latest releases for all current major language versions with fixes including several security-related issues:




The PHP development team announces the immediate availability of [these versions]. Six security-related issues in PHP were fixed in this release, as well as several security issues in bundled sqlite library (CVE-2015-3414, CVE-2015-3415, CVE-2015-3416). All PHP users are encouraged to upgrade to [the latest version for their current installation].


As always, you can get these latest downloads from the main downloads site or windows.php.net for the Windows binaries. Other fixes can be found in the release related list in the Changelog.


Link: http://php.net/

SimplestStatus — An Enhanced Enum Implementation for Any Version of Rails

While working on a recent project, I ended up with three different models with integer-type status columns and nearly identical status-related functionality. They looked something like this:




class Post < ActiveRecord::Base DRAFT = 0 PREVIEW = 1 PUBLISHED = 2 ARCHIVED = 3 STATUSES = { DRAFT => :draft, PREVIEW => :preview, PUBLISHED => :published, ARCHIVED => :archived } STATUSES.each do |value, name| scope name, -> { where(status: value) } define_method "#{name}?" do status == value end define_method name do update_attributes(status: value) end end validates :status, presence: true, inclusion: { in: STATUSES.keys } end


Having an integer-type status column gave me more flexibility over the number of statuses — as well as the flexibility to change the name of a status without having to make any database migrations (which would have been the case if I was storing strings). In my case, this was worth the tradeoff of the database having a different understanding of the data than the application.



After the third model, it was time to DRY things up. First, I thought about the simplest DSL to get me all the status functionality I needed, which led to the following:




class Post < ActiveRecord::Base statuses :draft, :preview, :published, :archived end


As a result, SimplestStatus was born!


Enter Enum



After implementing an extendable module (SimplestStatus) with the statuses DSL, I ran the idea past Mike, who mentioned the whole idea seemed just like enum. At the time, I hadn't heard of enum before.



If you're in that same boat, enum is a model-level method introduced in Rails 4.1 that wraps integer-type fields and provides a convenient set of functionality:




class Post < ActiveRecord::Base enum status: [ :draft, :preview, :published, :archived ] # or enum status: { draft: 0, preview: 1, published: 2, archived: 3 } end


This will get you class-level scopes as well as instance level setters and predicate methods — all things I had implemented myself in SimplestStatus. So why go with SimplestStatus?



Why SimplestStatus?



Compatibility



SimplestStatus's biggest advantage over enum is that it doesn't depend on a certain version of Rails. It works with practically every version (only tested as far back as 2.0.5, but may well work fine with earlier versions than that).



Reader Methods and Constants



If a field is backed by an integer column, I think there's value in exposing the integer to the application. Say you wanted to implement a Post#next_status method that cycles through the list of statuses:




class Post < ActiveRecord::Base extend SimplestStatus statuses :draft, :preview, :published, :archived def next_status Post.statuses[(status + 1) % Post.statuses.size] end end


Looking at enum, I wasn't a huge fan of the way it overwrote the reader method:




post.status # => 'draft'


SimplestStatus generates constants matching each status's name:




Post::DRAFT # => 0 Post::PREVIEW # => 1 Post::PUBLISHED # => 2 Post::ARCHIVED # => 3


Rather than having to remember the underlying integers, constants provide an expressive way to look up values. I found these helpful when setting up factories:




FactoryGirl.define do factory :post do # ... status Post::PUBLISHED # ... end trait :archived do status Post::ARCHIVED end end


Label Methods



Let's say we added a status :crowd_favorite to our list on the Post model.



With enum, you call post.status and get a string matching the original name you gave it:




post.status # => 'crowd_favorite'


For use in a view or form, you'd probably end up capitalizing/titleizing everywhere.



SimplestStatus provides a #status_label method:




post.status_label # => 'Crowd Favorite'


It also provides a label-friendly list of statuses for use in a form select:




Post.statuses.for_select # => [['Draft', 0], ['Preview', 1], ['Published', 2], ['Archived', 3], ['Crowd Favorite', 4]]


Validations



SimplestStatus will automatically add the following validations:




validates :status, presence: true, inclusion: { in: proc { statuses.values } }


..and More!



Check out the README to see all the other things you can do with SimplestStatus.



What's Next?



The original intent was to provide the simplest DSL possible to get all the convenient status functionality you could want. If there are things you find yourself doing around these integer-backed fields that you'd like to see in SimplestStatus, open a Github issue or leave a comment below. I'd love to hear feedback.



When you're working on a Rails app having models with a status — regardless of the Rails version — consider SimplestStatus!

I haven’t run beta OS software in years, but I’m s…


I haven’t run beta OS software in years, but I’m sorely tempted by the new iPad goodies in iOS 9.


2015年6月12日星期五

Site News: Popular Posts for the Week of 06.12.2015

Popular posts from PHPDeveloper.org for the past week:

Lo&iuml;c Chardonne: Symfony Differently - part 1: Introduction


Loïc Chardonne has kicked off a new series of posts on his site that talk about doing "Symfony Differently" and some things to consider/change to increase your Symfony application's performance.




Symfony is an amazing HTTP framework which powers high traffic websites. Performance shouldn't be a concern when first creating a website, because between the time it is launched and the time it actually has a high traffic many things that we didn't expect in the first days will happen: requirements will change, user behavior will change, even the team can change.



Optimizing applications has an impact over maintenance, and making it harder to change right from the beginning might not be the best option. However when the need of performance actually arises, we need to tackle it. This series of articles is about this specific moment, and how to tackle it in a pragmatic way.




He starts with a basic project (Acme) and works through the process of adding a new feature to it: buying an item. He talks about the team they have to work with and the architecture of his sample application (a frontend application mostly). He then works through the data structure and flow of the new feature and other functionality that should be included. He ends the post with a bit of a wrap-up of this first part and talks about the next part in the series where the application will actually be bootstrapped.


Link: http://gnugat.github.io/2015/06/03/sf-differently-part-1-introduction.html

Ed Zynda: Aspect Oriented PHP And The Interceptor Pattern


Ed Zynda has a recent post to his site looking at the use of the Interceptor design pattern with the aspect oriented methodology in PHP. He doesn't get into the basic concepts of AOP, so you might want to find out a bit more in other places. It's not a necessity, though, as his code examples are easy enough to follow along.



There are many ways to modify the behavior of existing code with actually changing the core logic. Some patterns you might be familiar with are the decorator pattern or the observer pattern. Both allow you to take another object and modify the behavior by wrapping your modifications around the original code. One pattern you might not be familiar with though, is the interceptor pattern.


He first helps you install the AOP-PHP extension to provide some of the necessary PHP functions. From there he talks about using some of the functions that intercept function calls and perform an action. He shows examples of it using:



  • aop_add_before
  • aop_add_after
  • aop_add_around


He also shows how to modify arguments during execution and changing return variables when the execution of the function is completed.


Link: http://www.edzynda.com/aspect-oriented-php-and-the-interceptor-pattern/

PHP Roundtable: 022: All About PSR-7


The PHP RoundTable podcast has posted their latest episode - Episode #22: All About PSR-7 (the recently accepted PHP-FIG standard for an HTTP interface layer).



PSR-7 is the latest accepted member to the PHP FIG's standards library. We discuss what PSR-7 is, how it utilizes streams, immutability & middleware, and how it will affects you as a developer.


You can catch this latest episode either through the embedded video player or directly on YouTube. If you enjoy the show, be sure to subscribe to their feed or follow them on Twitter.


Link: https://www.phproundtable.com/episode/psr-7-streams-immutability-middleware-oh-my

Laravel Podcast: Episode 29: PHP, Sublime Text, & Decorative Urns.


The Laravel Podcast, hosted by Matt Stauffer with guests Taylor Otwell and Jeffrey Way, has posted their latest episode - Episode 29: PHP, Sublime Text, & Decorative Urns..



In this episode, the crew discusses 20 years of PHP, their favorite PHP features, Sublime Text, PHP Storm, Nintendo, and Jeffrey's first programming job.


You can listen to this latest episode in a few different ways - either through the in-page player, grabbing the mp3 or subscribing to their feed to get this and future episodes as they're released.


Link: http://www.laravelpodcast.com/episodes/12992-episode-29-php-sublime-text-decorative-urns

PHP.net: PHP 7.0.0 Alpha 1 Released


The first release on the path to PHP7 has officially been released according to this new post on the main PHP.net website - PHP 7.0.0 Alpha 1.



The PHP development team announces the immediate availability of PHP 7.0.0 Alpha 1. This release marks the beginning of the PHP 7 major series. All users of PHP are encouraged to test this version carefully, and report any bugs and incompatibilities in the bug tracking system. PHP 7.0.0 Alpha 1 comes with new version of the Zend Engine with features. [...] For more information on the new features and other changes, you can read the NEWS file or the or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive.


As with other alpha PHP releases, you can download this preview version from the downloads page or windows.php.net/qa website for the binaries.


Link: http://php.net/archive/2015.php#id2015-06-11-3

Searching Serialized Fields in Rails Using Postgres Arrays

In Rails, ActiveRecord allows you store and retrieve data structures like arrays and hashes in a single string or text-type database column through application-level serialization.



It is a common pattern with models having fields like tags or nicknames, where you want to be able to store an arbitrary list of strings:




class Post < ActiveRecord::Base serialize :tags end


This is all fine n' dandy until you're like, "I want to find all posts tagged with either 'hobbits' or 'gandalf'!" Well..



simply


The database only knows it has a string, not a comma-separated list of strings. It is possible to search application-level serialized fields, but it's pretty hacky and brittle:




class Post scope :including_all_tags, -> (tags) { where(matching_tag_query(tags, 'AND')) } scope :including_any_tags, -> (tags) { where(matching_tag_query(tags, 'OR')) } private def matching_tag_query(tags, condition_separator = 'OR') tags.map { |tag| "(tags LIKE '%#{tag}%')" }.join(" #{condition_separator} ") end end # In use Post.including_all_tags(['hobbits', 'gandalf']) Post.including_any_tags(['hobbits', 'gandalf'])


This approach builds a WHERE condition and matches against the given tags, which grows and becomes increasingly inefficient as the number of searched tags increases. Also, if you have tags like gandalf and gandalf-the-grey, you'd get false positives with the above example. While passable for simple cases, there's got to be a better way! Fortunately for us, along comes Postgres.



types



PostgreSQL Arrays



Postgres has built-in array-type columns, which we can take advantage of in our Rails 4.X apps with the postgres_ext gem. What does this mean for our Rails apps? If we can store arrays in a single database column, then our database and application have the same understanding of the structure of the data. This isn't possible with the out-of-the-box serialization model. Most importantly, we can use SQL to effectively search inside our array-type columns.



With PostgresExt installed, we can add an array: true flag to string/text columns:




class PostgresHaveMyBabiesMigration < Migration def change create_table :posts do |t| t.text :tags, array: true end end end


Now, the model is no longer concerned with serializing the :tags field:




class Post < ActiveRecord::Base # crickets end


Searching



As mentioned, one of the primary benefits of Postgres's array-type column is the enhanced searchability through array-specific SQL. The Postgres Extensions gem unlocks a number of array operators and functions for usage in SQL strings. Let's take a look at operators in both their SQL and Arel forms. If you're unfamiliar with Arel, check out this post where I expand on its usefulness.



Overlap Operator



The overlap operator (&&) is useful when you're comparing two arrays to see if they share one or more elements in common.



In SQL:




SELECT * FROM posts WHERE posts.tags && '{hobbits,gandalf}'


Utilizing Arel:




Post.where(Post.arel_table[:tags].overlap(['hobbits', 'gandalf'])) # or Post.where.overlap(tags: ['hobbits', 'gandalf'])


These queries would return any posts having either 'hobbit' or 'gandalf' as a tag.



Contains Operator



The contains operator (@>) is useful when you're looking for arrays that contain all the elements of another.



In SQL:




SELECT * FROM posts WHERE posts.tags @> '{hobbits,gandalf}'


Utilizing Arel:




Post.where(Post.arel_table[:tags].contains(['hobbits', 'gandalf'])) # or Post.where.contains(tags: ['hobbits', 'gandalf'])


These queries would return any posts having both the 'hobbits' and 'gandalf' tags.



mmm



Wrapping Up



Postgres is awesome. The array extensions are magical. Instead of application-level serialization, let Postgres handle array persistance for you. It unifies the understanding of array-type data between the database and application and simplifies searching.

2015年6月11日星期四

Site News: Blast from the Past - One Year Ago in PHP

Here's what was popular in the PHP community one year ago today:

That Podcast: Episode 19: The one where Taylor joins the conversation


That Podcast has posted their latest episode today, #19 - The One Where Taylor Joins the Conversation featuring special guest Taylor Otwell, creator of the Laravel framework.



Some time ago Dave had the idea to bring Taylor Otwell, creator of Laravel, on the show as he fit our general theme very well, he's a dad, a programmer, and is definitely an entrepreneur. Arrangements were made and since then, Beau has launched his first two Laravel apps and has started to use both Forge and Envoyer. Dave, too, has worked with Laravel a bit in the past, so it was a great time to Taylor on the show to talk life and shop.


You can listen to their latest episode either through the in-page audio player or by downloading the mp3 directly. If you enjoy the episode be sure to either subscribe to their newsletter or just subscribe to their feed for the latest episodes as they're released.


Link: https://thatpodcast.io/episodes/episode-19-the-one-where-taylor-joins-the-conversation

SitePoint PHP Blog: Multiple Editors per Node in Drupal 7


The SitePoint PHP blog has posted a new Drupal tutorial about allowing multiple editors to work on the same node of content.



have encountered a practical use case where the default configuration options are not enough. Namely, if you need to have multiple users with access to edit a particular node of a given type but without them necessarily having access to edit others of the same type. In other words, the next great article should be editable by Laura and Glenn but not by their colleagues. However, out of the box, users of a particular role can be masters either of their own content or of all content of a certain type. So this is not immediately possible. In this article I am going to show you my solution to this problem in the form of a simple custom module called editor_list.


He walks you through the process, first creating the .info file needed to define the module and the changes needed for the .module file. He creates a few helper functions to get the editor listing for a node and its matching access rules. With the module created he then gets into building the fields, again making helper methods to get the editors for the fields. Finally he "tidies up" and adds an "Authored on" section to the node editor with a helper function to receive and handle the results of this field when the form is submitted.


Link: http://www.sitepoint.com/multiple-editors-per-node-drupal-7/

Matt Stauffer: Creating Artisan commands with the new, simpler syntax in Laravel 5.1


Matt Stauffer has posted the latest in his "What's New in Laravel 5" series today with a look at the changes in creating Artisan commands with a newer, simpler syntax.



If you're not familiar with Artisan commands, they're command-line functions that you can run to interact with your Laravel application. If you run php artisan from the command line in any Laravel application directory, you'll see a list of all of the Artisan commands available for each app. As you can see, Laravel comes with quite a few enabled out of the box.


He starts with a look at the old way of creating the commands using the "artisan make:console" command to build the class and an example of its contents. This version requires a good bit of extra code to reference things like arguments and define required parameters. He then compares this with the new way with a much simpler syntax and reduced about of code overall. One of the main differences he mentions is the concept of a "signature" for the command - a specially formatted string that defines configuration such as required and optional parameters. He finishes the post with a few examples of these signatures.


Link: https://mattstauffer.co/blog/creating-artisan-commands-with-the-new-simpler-syntax-in-laravel-5.1

Zend Developer Zone: #20yearsofphp - A Timeline of Tweets


In remembrance of the 20th anniversary of PHP, the Zend Developer Zone has created a new post sharing tweets from the PHP Community Twitter account covering the history of PHP.



My friend - and PHP Community Old Guard - Ben (@ramsey) Ramsey did something awesome for PHP's 20th, he tweeted out the PHP timeline. I've gathered them all here to celebrate both PHP and the work he put into this project.


The post shares a long list of the tweets from the account mentioning the happenings of the last twenty years. It starts with the first release of the language back in 1995 (by Rasmus Lerdorf) and goes all the way up through the present day. It's been quite a ride over the last 20 years. If you're new to the PHP community or just want to relive some of the memories of the past, check out the full post!


Link: http://devzone.zend.com/6178/20yearsofphp-a-timeline-of-tweets/

Dealing With the ROT

In my latest post for Smashing Magazine I explore how to deal with redundant, out of date and trivial content.