SitePoint PHPCreating Strictly Typed Arrays and Collections in PHP (24.3.2017, 16:00 UTC)

One of the language features announced back in PHP 5.6 was the addition of the ... token to denote that a function or method accepts a variable length of arguments.

Something I rarely see mentioned is that it’s possible to combine this feature with type hints to essentially create typed arrays.

For example, we could have a Movie class with a method to set an array of air dates that only accepts DateTimeImmutable objects:


class Movie {
  private $dates = [];

  public function setAirDates(\DateTimeImmutable ...$dates) {
    $this->dates = $dates;

  public function getAirDates() {
    return $this->dates;

Collection of colored balls of same type

We can now pass a variable number of separate DateTimeImmutable objects to the setAirDates() method:


$movie = new Movie();

  \DateTimeImmutable::createFromFormat('Y-m-d', '2017-01-28'),
  \DateTimeImmutable::createFromFormat('Y-m-d', '2017-02-22')

If we were to pass something else than a DateTimeImmutable, a string for example, a fatal error would be thrown:

Catchable fatal error: Argument 1 passed to Movie::setAirDates() must be an instance of DateTimeImmutable, string given.

If we instead already had an array of DateTimeImmutable objects that we wanted to pass to setAirDates(), we could again use the ... token, but this time to unpack them:


$dates = [
  \DateTimeImmutable::createFromFormat('Y-m-d', '2017-01-28'),
  \DateTimeImmutable::createFromFormat('Y-m-d', '2017-02-22'),

$movie = new Movie();

If the array were to contain a value that is not of the expected type, we would still get the fatal error mentioned earlier.

Additionally, we can use scalar types the same way starting from PHP 7. For example, we can add a method to set a list of ratings as floats on our Movie class:



class Movie {
  private $dates = [];
  private $ratings = [];

  public function setAirDates(\DateTimeImmutable ...$dates) { /* ... */ }
  public function getAirDates() : array { /* ... */ }

  public function setRatings(float ...$ratings) {
    $this->ratings = $ratings;

  public function getAverageRating() : float {
    if (empty($this->ratings)) {
      return 0;

    $total = 0;

    foreach ($this->ratings as $rating) {
      $total += $rating;

    return $total / count($this->ratings);

Again, this ensures that the ratings property will always contain floats without us having to loop over all the contents to validate them. So now we can easily do some math operations on them in getAverageRating(), without having to worry about invalid types.

Problems with This Kind of Typed Arrays

One of the downsides of using this feature as typed arrays is that we can only define one such array per method. Let’s say we wanted to have a Movie class that expects a list of air dates together with a list of ratings in the constructor, instead of setting them later via optional methods. This would be impossible with the method used above.

Another problem is that when using PHP 7, the return types of our get() methods would still have to be “array”, which is often too generic.

Solution: Collection Classes

To fix both problems, we can simply inject our typed arrays inside so-called “collection” classes. This also improves our separation of concerns, because we can now move the calculation method for the average rating to the relevant collection class:



class Ratings {
  private $ratings;

  public function __construct(float ...$ratings) {
    $this->ratings = $ratings;

  public function getAverage() : float {
    if (empty($this->ratings)) {
      return 0;

    $total = 0;

    foreach ($this->ratings as $rating) {
      $total += $rating;

    return $total / count($this->ratings);

Notice how we’re still using a list of typed arguments with a variable length in our constructor, which saves us the trouble of looping over each rating to check its type.

Continue reading %Creating Strictly Typed Arrays and Collections in PHP%

Paul M. JonesRegarding A Recent Event (24.3.2017, 14:15 UTC)
KING HENRY V: We judge no less. Uncle of Exeter,
    Enlarge the man committed yesterday,
    That rail'd against our person: we consider
    it was excess of wine that set him on;
    And on his more advice we pardon him.

SCROOP: That's mercy, but too much security:
    Let him be punish'd, sovereign, lest example
    Breed, by his sufferance, more of such a kind.

KING HENRY V: O, let us yet be merciful.

CAMBRIDGE: So may your highness, and yet punish too.

GREY: Sir,
    You show great mercy, if you give him life,
    After the taste of much correction.

KING HENRY V: Alas, your too much love and care of me
    Are heavy orisons 'gainst this poor wretch!
    If little faults, proceeding on distemper,
    Shall not be wink'd at, how shall we stretch our eye
    When capital crimes, chew'd, swallow'd and digested,
    Appear before us? We'll yet enlarge that man,
    Though Cambridge, Scroop and Grey, in their dear care
    And tender preservation of our person,
    Would have him punished. And now to our French causes:
    Who are the late commissioners?

CAMBRIDGE: I one, my lord:
    Your highness bade me ask for it to-day.

SCROOP: So did you me, my liege.

GREY: And I, my royal sovereign.

KING HENRY V: Then, Richard Earl of Cambridge, there is yours;
    There yours, Lord Scroop of Masham; and, sir knight,
    Grey of Northumberland, this same is yours:
    Read them; and know, I know your worthiness.
    My Lord of Westmoreland, and uncle Exeter,
    We will aboard to night. Why, how now, gentlemen!
    What see you in those papers that you lose
    So much complexion? Look ye, how they change!
    Their cheeks are paper. Why, what read you there
    That hath so cowarded and chased your blood
    Out of appearance?

CAMBRIDGE: I do confess my fault;
    And do submit me to your highness' mercy.

GREY    |
        | To which we all appeal.

KING HENRY V: The mercy that was quick in us but late,
    By your own counsel is suppress'd and kill'd:
    You must not dare, for shame, to talk of mercy;
    For your own reasons turn into your bosoms,
    As dogs upon their masters, worrying you.

I hope this is the last thing I will have to say on the matter.

PHP ClassesPHP and JavaScript Innovation Award Report March 2017 Edition - December 2016 nominees (23.3.2017, 07:34 UTC)
By Manuel Lemos
This is the March edition of the Innovation Award podcast hangout recorded by Manuel Lemos and Arturs Sosins to comment on the outstanding features of all the past month nominees and winners PHP and JavaScript packages, the prizes that the authors earned, starting with the nominees from the month of December 2016.

Listen to the podcast, or watch the hangout video to learn why the nominated packages were considered to be innovative, as well the current rankings of the Innovation Award Championship by author and by country.
SitePoint PHPParallel Programming with Pthreads in PHP – the Fundamentals (22.3.2017, 16:00 UTC)

PHP developers seem to rarely utilise parallelism. The appeal of the simplicity of synchronous, single-threaded programming certainly is high, but sometimes the usage of a little concurrency can bring some worthwhile performance improvements.

In this article, we will be taking a look at how threading can be achieved in PHP with the pthreads extension. This will require a ZTS (Zend Thread Safety) version of PHP 7.x installed, along with the pthreads v3 installed. (At the time of writing, PHP 7.1 users will need to install from the master branch of the pthreads repo - see this article's section for details on building third-party extensions from source.)

Just as a quick clarification: pthreads v2 targets PHP 5.x and is no longer supported; pthreads v3 targets PHP 7.x and is being actively developed.

Parallel execution abstract image

A big thank you to Joe Watkins (creator of the pthreads extension) for proofreading and helping to improve my article!

When Not to Use Pthreads

Before we move on, I would first like to clarify when you should not (as well as cannot) use the pthreads extension.

In pthreads v2, the recommendation was that pthreads should not be used in a web server environment (i.e. in an FCGI process). As of pthreads v3, this recommendation has been enforced, so now you simply cannot use it in a web server environment. The two prominent reasons for this are:

  1. It is not safe to use multiple threads in such an environment (causing IO issues, amongst other problems).
  2. It does not scale well. For example, let's say you have a PHP script that creates a new thread to handle some work, and that script is executed upon each request. This means that for each request, your application will create one new thread (this is a 1:1 threading model - one thread to one request). If your application is serving 1,000 requests per second, then it is creating 1,000 threads per second! Having this many threads running on a single machine will quickly inundate it, and the problem will only be exacerbated as the request rate increases.

That's why threading is not a good solution in such an environment. If you're looking for threading as a solution to IO-blocking tasks (such as performing HTTP requests), then let me point you in the direction of asynchronous programming, which can be achieved via frameworks such as Amp. SitePoint has released some excellent articles that cover this topic (such as writing asynchronous libraries and Modding Minecraft in PHP), in case you're interested.

With that out of the way, let's jump straight into things!

Handling One-off Tasks

Sometimes, you will want to handle one-off tasks in a multi-threaded way (such as performing some IO-bound task). In such instances, the Thread class may be used to create a new thread and run some unit of work in that separate thread.

For example:

$task = new class extends Thread {
    private $response;

    public function run()
        $content = file_get_contents("");
        preg_match("~~", $content, $matches);
        $this->response = $matches[1];

$task->start() && $task->join();

var_dump($task->response); // string(6) "Google"

In the above, the run method is our unit of work that will be executed inside of the new thread. When invoking Thread::start, the new thread is spawned and the run method is invoked. We then join the spawned thread back to the main thread (via Thread::join), which will block until the separate thread has finished executing. This ensures that the task has finished executing before we attempt to output the result (stored in $task->response).

Continue reading %Parallel Programming with Pthreads in PHP – the Fundamentals%

Nomad PHPPieces of Auth (22.3.2017, 00:13 UTC)

June 2017
Presented By

Chris Cornutt
June 22, 2017
20:00 CDT

The post Pieces of Auth appeared first on Nomad PHP.

Voices of the ElePHPantInterview with Sherrie Rhode (21.3.2017, 17:24 UTC) Link
PHP ClassesFaster PHP Social Login with a PHP OpenID Connect PHP OAuth Library (21.3.2017, 13:36 UTC)
By Manuel Lemos
Many applications use OAuth authenticate users using their information retrieved from social network accounts with their permission.

However, each social network requires an additional API call to retrieve those user details. That API call is specific to each network, so its URL and parameters vary.

OpenID Connect is an extension of the OAuth2 protocol that allows to retrieve the user details without additional API calls.

Read this article to learn how it works and how you can benefit from OpenID Connect to get the user details faster without social network specific API calls.
PHP ClassesFaster PHP Social Login with a PHP OpenID Connect PHP OAuth Library (21.3.2017, 13:03 UTC)
By Manuel Lemos
Many applications use OAuth authenticate users using their information retrieved from social network accounts with their permission.

However, each social network requires an additional API call to retrieve those user details. That API call is specific to each network, so its URL and parameters vary.

OpenID Connect is an extension of the OAuth2 protocol that allows to retrieve the user details without additional API calls.

Read this article to learn how it works and how you can benefit from OpenID Connect to get the user details faster without social network specific API calls.
Qafoo - PHPHow to Perform Extract Service Refactoring When You Don't Have Tests (21.3.2017, 08:54 UTC)
When you are refactoring in a legacy codebase, the goal is often to reduce complexity or separate concerns from classes, methods and functions that do too much work themselves. Primary candidates for refactoring are often controller classes or use-case oriented service classes (such as a UserService). Extracting new service classes is one popular refactoring to separate concerns, but without tests it is dangerous because there are many ways to break your original code – we show you how this can still be done.
SitePoint PHPSourcehunt – Build a Medium Exporter + Cool New Libs! (20.3.2017, 16:00 UTC)

It's time for our monthly hunt for new open source libraries to use and contribute to!

If you're new to Sourcehunt, it's our monthly post for promoting open source projects that seem interesting or promising and could use help in terms of Github stars or pull requests.

It's our way of giving back - promoting projects that we use (or could use) so that they gain enough exposure to attract a wider audience, a powerful community and, possibly, new contributors or sponsors.

Sourcehunt logo

We've had a lot of fantastic submissions this month, so let's dive in!

rethinkphp/json-validator [28 ★]

A Json Validator that designed to be elegant and easy to use.

Made by the author of the Blink framework, json-validator's only purpose is to make sure a data structure conforms to the pre-defined specification. It currently supports int, double, bool, string, number, array, and object, but also lets you define fully custom types, like so:

$validator->defineType('User', [
    'name' => 'string',
    'gender' => 'string',
    'age' => '?integer',

You can also define them in callables:

$validator->defineType('timestamp', function ($value) {
    if ((!is_string($value) && !is_numeric($value)) || strtotime($value) === false) {
        return false;

    $date = date_parse($value);

    return checkdate($date['month'], $date['day'], $date['year']);

The library is very new and could use contributions - everything from the docs to features needs work, so it's a great opportunity to contribute.

Nerdmind/Blog [20 ★]

This minimalistic and mobile-friendly blogging engine, while leaving much to be desired in the visual department, is a practical quick-fix for anyone looking to start a blog without the baggage of larger system weighing them down.

It does seem somewhat like a learning experience for the author, so why not jump in, identify some issues (lots of antipatterns right off the bat), and maybe fix some while you're at it? Perhaps both of you can learn from the experience.

violet-php/streaming-json-encoder [125 ★]

This streaming JSON encoder lets you process and send large JSON files without hitting the memory limit. As described in the README:

Streaming JSON Encoder is a PHP library that provides a set of classes to help with encoding JSON in a streaming manner, i.e. allowing you to encode the JSON document bit by bit rather than encoding the whole document at once. Compared to the built in json_encode function, there are two main advantages:

  • You will not need to load the entire data set into memory, as the encoder supports iterating over both arrays and any kind of iterators, like generators, for example.
  • You will not need to load the entire resulting JSON document into the memory, since the JSON document will be encoded value by value and it's possible to output the encoded document piece by piece.

It also provides a PSR-7 compatible stream for those kinds of frameworks.

The package could use more tutorials, tests, and usage examples, so get on it if you're eager - we'll pay!

dsentker/phpinsights [2 ★]

This simple but effective wrapper around Google PageSpeed Insights is incredibly useful for testing pipelines when you want to track your pagespeed score across time or commit.

$uri = '';
$caller = new \PhpInsights\InsightsCaller('your-google-api-key-here', 'de');
$response = $caller->getResponse($uri, \PhpInsights\InsightsCaller::STRATEGY_MOBILE);
$result = $response->getMappedResult();

var_dump($result->getSpeedScore()); // 100
var_dump($result->getUsabilityScore()); // 100

Note that you need to get an API key from the Google Dev console bef

Truncated by Planet PHP, read more at the original (another 1246 bytes)

LinksRSS 0.92   RDF 1.
Atom Feed   100% Popoon
PHP5 powered   PEAR
ButtonsPlanet PHP   Planet PHP
Planet PHP