Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

SitePoint PHP Blog:
Sourcehunt PHP: Contribute to Crypto, Validation, Payments…
Nov 19, 2015 @ 11:17:54

The SitePoint PHP blog has published the first edition of their "Sourcehunt" effort, sharing several PHP libraries to promote them and give them wider exposure to the community at large. In this post they talk about tools covering a wide range of functionality including cryptography, validation, user agent parsing and "humanizing" strings.

Last month, we introduced a new effort called Sourcehunt – a category of post intended to direct attention to less popular open source projects that show promise and need exposure. We’ve called for new submissions and accumulated an impressive list.

Included in their list for this edition are tools like:

...and many more. A summary of the features, code and output examples are provided for most of the tools mentioned and the number of GitHub stars at the time of the posting is listed next to each library name.

tagged: sourcehunt sitepoint library tool spotlight example summary

Link: http://www.sitepoint.com/sourcehunt-php-contribute-to-crypto-validation-payments/

Gonzalo Ayuso:
POST Request logger using websockets
Nov 17, 2015 @ 10:25:32

In this post to his site Gonzalo Ayuso shows you how to create a logger for your POST requests and their information with a bit of helpful code and Websockets.

Last days I’ve been working with background geolocation with an ionic application. There’s a cool plugin to do that. [...] Basically this plugin performs a POST request to the server with the GPS data. [...] I can develop a simple Silex application with a POST route and log the request in a file or flush those request to the console. This’d have been easy but as far as I’m a big fan of WebSockets (yes I must admit that I want to use WebSockets everywhere :) I had one idea in my mind.

He shows the creation of a simple Silex-based application with just two endpoints (channel that handles both GET and POST) that uses the Guzzle HTTP library to listen on the Websockets port for incoming connections. He then shows how to add the code necessary on the frontend (using express) to send the POST data automatically to the waiting Silex application. He's provided the full working code for the example on his GitHub account as well so you can see it fully fleshed out.

tagged: websockets post log silex tutorial example gps plugin automatic debug

Link: http://gonzalo123.com/2015/11/16/post-request-logger-using-websockets/

Madewithlove Blog:
Thread carefully
Nov 16, 2015 @ 11:55:58

In a post to the Madewithlove blog Maxime Fabre takes a look at threading in PHP using the pthreads support that can be included into your PHP installation.

As far as I can remember, PHP has always had a terrible reputation at handling very heavy (or asynchronous) tasks. [...] But PHP can do threading, and more importantly it's a lot easier than you probably think.

[...] In this article I'm going to dive into the pthreads extension (short for POSIX Threads). It has been around for a while (since 2012) but I feel like too many people forget it exists or assume it is going to be painful to use – mostly because the official documentation is rather slim about it.

They start by getting the pthreads support installed locally (it assumes you use OS X and the "brew" package manager but it can be installed manually too). The article starts off by defining some basic nomenclature from the pthreads world and gives a diagram of how it all fits together. From there it gets into some examples, showing a simple thread class to fetch Google results and how to fire off multiple instances at the same time. They then extend this even further and look at the concept of "workers" and using them to manage individual jobs. It then moves up the next level and looks at "pools" of workers and processing multiple workers at the same time.

There's also a section dealing with one "gotcha" that can happen with class inheritance between parent and child threads. They show how to work around this with a custom Worker class that performs the autoloading for you and is executed at the start of a Pool. Finally they cover the messaging between the child threads and, as a bonus, how threading could be used in a command bus setup.

tagged: threading tutorial pthreads example worker thread pool process commandbus messaging

Link: http://blog.madewithlove.be/post/thread-carefully/

Cees-Jan Kiewiet:
ReactPHP: HTTP Client
Nov 05, 2015 @ 12:05:14

Cees-Jan Kiewiet has a post on his site focusing on the HTTP client side of the functionality offered by the ReactPHP. In this post he covers the basics of installation and usage with plenty of code examples (and screencasts of it in action).

Aside from a HTTP component ReactPHP also has a HTTP Client component that lets your send out HTTP requests. It is incredibly handy when you need to communicate with for example elasticsearch's REST API, AWS platform through their SDK or the RIPE Atlas API.

He walks you through the simple installation of the library (via Composer) and the code to send a simple request to an example.com domain, returning the HTML contents of the page. He then gets to some more complex examples: sending two requests at the same time, streaming the response body as it arrives and an example based on community feedback - streaming Twitter data. He ends the post with a community example showing the use of the Buzz HTTP client to make simple requests.

tagged: reactphp http client example stream twitter screencast

Link: http://blog.wyrihaximus.net/2015/11/reactphp-http-client/

Lorna Mitchell:
PHP: Calling Methods on Non-Objects
Oct 19, 2015 @ 10:53:57

In a quick post to her site Lorna Mitchell describes a small difference in error messaging that's changed between PHP versions when trying to call methods on non-objects between versions 5.5, 5.6 and the upcoming PHP 7.

PHP has subtly changed the wording of this error between various versions of the language, which can trip up your log aggregators when you upgrade so I thought I'd give a quick rundown of the changes around the "call to member function on non-object" error in PHP, up to and including PHP 7 which has an entirely new error handling approach.

She includes examples of the error messages for PHP 5.5 and 5.6, differing only in how they report back the type of the variable the method was called on (one gets more specific). In PHP 7, however, the message is different because of the major overhaul that error handling has gotten. The new Error inheritance model still has it throw a fatal but it also notes it's an uncaught error which can be caught with the same try/catch as any other exception.

tagged: object error message version php5 php7 example output uncaught

Link: http://www.lornajane.net/posts/2015/php-calling-methods-on-non-objects

Lorna Mitchell:
New in PHP 7: null coalesce operator
Sep 30, 2015 @ 10:51:52

Lorna Mitchell has a post to her site talking about a new addition to PHP in the upcoming major release of PHP 7 - the null coalesce operator. Despite its slightly confusing name, the operator is very handy for certain use cases with the ternary syntax.

Not the catchiest name for an operator, but PHP 7 brings in the rather handy null coalesce so I thought I'd share an example. In PHP 5, we already have a ternary operator, which tests a value, and then returns the second element if that returns true and the third if it doesn't. [...] There is also a shorthand for that which allows you to skip the second element if it's the same as the first one.

[...] In PHP 7 we additionally get the ?? operator which rather than indicating extreme confusion which is how I would usually use two question marks together instead allows us to chain together a string of values.

She includes an example of this new operator in use, chaining together a simple expression and showing the resulting output. It's a little confusing at first, but then if you remember it reads left to right it clears it up a bit.

tagged: null coalesce operator php7 feature example

Link: http://www.lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator

Hannes Van De Vreken:
Why You Should Avoid Over-Abstracting
Sep 29, 2015 @ 09:35:24

Hannes Van De Vreken has some advice for the PHP developers out there working on projects that make use of some form of abstraction - don't over-abstract. In his case, he's talking more about the use of abstract classes and where they fit into a good overall project structure.

Some time ago I started working on an existing project, so I read the documentation before diving in. At the top of the contributing.md file there was this sentence: “Abstract when possible”. Quickly I learned the project contained more abstract classes than a normal project. This leads to too highly coupled, and often unchangeable code.

This post is dedicated on explaining why “abstract when possible” isn’t good advice. Not only in PHP, but in all programming languages.

He starts with some of the common issues he sees with abstract classes including the over-complication of abstract methods and defining all dependencies the children need even though the abstract class doesn't. To help resolve these issues he recommends the use of traits. These traits include the dependencies needed by the child classes (for example only things needed for a CSV export, not other types). He includes all the code for this particular example. Finally he looks at situations where abstract classes are okay to use. He uses the LeagueEvent package as an example, showing how it creates a listener interface and an abstract class that contains an equality check function. He shows how to refactor this as a trait too.

tagged: abstraction overuse trait tutorial leagueevent example

Link: http://blog.madewithlove.be/post/on-over-abstracting/

SitePoint PHP Blog:
Demystifying RegEx with Practical Examples
Sep 25, 2015 @ 12:30:19

On the SitePoint PHP blog they've posted a tutorial from author Nicola Pietroluongo that wants to help demystify regular expressions with a few more real-world examples. He doesn't teach the foundations of regular expressions here and instead opts for a more "cookbook" approach with lots of little examples.

A regular expression is a sequence of characters used for parsing and manipulating strings. They are often used to perform searches, replace substrings and validate string data. This article provides tips, tricks, resources and steps for going through intricate regular expressions.

He starts with some basic tips around creating good regular expressions for your application: knowing the scenario you're matching, planning the requirements and implementing the match itself. His example expressions include matching for:

  • simple passwords matching a policy
  • valid URL matching
  • HTML tag patterns
  • finding duplicated words

Each example comes with the regular expression itself and an explanation of how it's doing the matching, breaking it down into each piece of the regex puzzle and how it relates to the match overall.

tagged: regularexpression regex practical example tutorial scenario requirements

Link: http://www.sitepoint.com/demystifying-regex-with-practical-examples/

Matt Stauffer:
Environment-Specific Configuration for CraftCMS Using PHPDotEnv
Sep 25, 2015 @ 10:13:21

In this post to his site Matt Stauffer shows a more real-word example of how the phpdotenv library can make configuration of your application simpler. He shows how it can be applied to a Craft CMS installation to manage domain-specific configuration details.

Craft is a fantastic CMS, but every CMS shows some pain points when you have a large team working on the same site at the same time. One of these points for me is Craft's native multi-environment configuration options, which allow you to define configuration options based on the domain name.

[...] This is great, but it's limited: You're hard-coding the configuration details into your code, which sometimes means putting sensitive information into your version control. Every developer's local installs either all have to have different domains, or if they use the same domain they need to all have the same configuration settings. And something just feels dirty about the codebase having such knowledge of every place it's going to be deployed.

He introduces the phpdotenv library and how you define its simple .env file with a basic INI structure. He then shows how to add the phpdotenv library to your installation:

  • adding it to the list of Composer installed libraries
  • update your front controller to load the configuration
  • define the .env file with your settings
  • ignore it via .gitignore

With these steps in place you can then update the Craft configuration with calls to getenv in all the right places to pull items from the phpdotenv configuration.

tagged: phpdotenv env configuration craftcms example environment tutorial

Link: https://mattstauffer.co/blog/environment-specific-configuration-for-craftcms-using-phpdotenv

Zend Developer Zone:
A new type of PHP, part 2: Scalar types
Sep 16, 2015 @ 09:09:26

The Zend Developer Zone has posted the second part of their series (from community member Larry Garfield) about scalar types in PHP 7, one of many features in this "coming soon" release. You can find part one of the series here.

In our last installment, we talked about the benefits of more robust variable typing in PHP 7, and specifically the new support for typed return values. That is already a big boon to the maintainability of our code, but PHP 7 goes a step further. So far, we’ve only talked about typing against classes and interfaces. We’ve been able to type against those (and arrays) for years. PHP 7, however, adds the ability to type against scalar values too, such as int, string, and float.

But wait. In PHP, most primitives are interchangeable. [...] Much the same as return types, scalar types offer greater clarity within the language as well as the ability to catch more bugs earlier. That, in turn, can help encourage more robust code in the first place, which benefits everybody.

He starts by looking at the four new types that have been added in PHP 7: int, float, string, and bool. He includes a code example showing each of them in use on class interfaces and functions. He steps through the code example, explaining how the return type checking is handled for each instance. He also talks about how return type hinting can also benefit static analysis tools, allowing them to potentially find bugs in return values easier than before. Finally he covers strict mode, the method for enforcing types in your code and preventing PHP from doing any "magic" type switching for you. He also includes a code example of this functionality and how, with it enabled, it would have caught an error in his example on a integer vs string input.

tagged: scalar type hints introduction php7 strict example

Link: http://devzone.zend.com/6622/a-new-type-of-php-part-2-scalar-types/