PHP ClassesBoosting the Visibility of Your PHP Projects with Data Mining and Business Intelligence (28.3.2017, 13:35 UTC)
By Manuel Lemos
If you ever tried to get attention to your Open Source software work but it did not get very far, now you can learn how to fix that.

Thanks to basic data mining techniques on search engine traffic statistics and business intelligence methods, it is possible to help you to optimize the content that you publish to promote your Open Source work beyond the traditional methods of publishing the code in a repository and waiting to see what happens.

Read this article and watch a demo video about search engine optimization tool that is being used to optimize the content of many Open Source projects to leverage the number of interested users.
Voices of the ElePHPantInterveiw with Thomas Gamble (28.3.2017, 10:00 UTC) Link
SitePoint PHPGame Development with ReactJS and PHP: How Compatible Are They? (27.3.2017, 16:00 UTC)

"I'd like to make a multiplayer, economy-based game. Something like Stardew Valley, but with none of the befriending aspects and a player-based economy."

Stardew valley

I started thinking about this the moment I decided to try and build a game using PHP and ReactJS. The trouble is that I knew nothing about the dynamics of multiplayer games, or how to think about and implement player-based economies.

I wasn't even sure that I knew enough about ReactJS to justify using it. I mean, the initial interface – where I focus heavily on the server and economic aspects of the game – is perfectly suited for ReactJS. But what about when I start to make the farming /interaction aspects? I love the idea of building an isometric interface around the economic system.

I once watched a talk, by dead_lugosi, where she described building a medieval game in PHP. Margaret inspired me, and that talk was one of the things that lead to me writing a book about JS game development. I became determined to write about my experience. Perhaps others could learn from my mistakes in this case, too.

The code for this part can be found at: I've tested it with PHP 7.1 and in a recent version of Google Chrome.

Setting Up The Back-end

The first thing I searched for was guidance on building multiplayer economies. I found an excellent StackOverflow thread in which folks explained various things to think about. I got about half-way through it before realizing I may be starting from the wrong place.

"First things first; I need a PHP server. I'm going to have a bunch of ReactJS clients, so I want something capable of high-concurrency (perhaps even Web Sockets). And it needs to be persistent: things must happen even when players aren't around."

I went to work setting up an async PHP server – to handle high concurrency and support web sockets. I added my recent work with PHP preprocessors to make things cleaner, and made the first couple of endpoints:

$host = new Aerys\Host();
$host->expose("*", 8080);

$host->use($router = Aerys\router());
$host->use($root = Aerys\root(.."/public"));

$web = process .."/routes/web.pre";

$api = process .."/routes/api.pre";

This is from config.pre

I decided to use Aerys for the HTTP and Web Socket portions of the application. This code looked very different compared to the Aerys docs, but that's because I had a good idea about what I needed.

The usual process for running an Aerys app was to use a command like:

vendor/bin/aerys -d -c config.php

That's a lot of code to keep repeating, and didn't handle the fact that I wanted to use PHP preprocessing. I created a loader file:

return Pre\processAndRequire(__DIR__ . "/config.pre");

This is from loader.php

...and installed my dependencies:

"require": {
    "amphp/aerys": "dev-amp_v2",
    "amphp/loop": "dev-master",
    "amphp/parallel": "dev-master",
    "league/container": "^2.2",
    "league/plates": "^3.3",
    "pre/short-closures": "^0.3.0"
"require-dev": {
    "phpunit/phpunit": "^6.0"

This is from composer.json

I wanted to use amphp/parallel, to move blocking code out of the async server, but it wouldn't install with a stable tag of amphp/aerys. That's why I went with the dev-amp_v2 branch.

Continue reading %Game Development with ReactJS and PHP: How Compatible Are They?%

Christian WeiskeImproving TYPO3 docker cache warming speed (27.3.2017, 05:28 UTC)

Warming the page cache after a production deployment took up to two minutes for certain TYPO3 pages. We got that down to mere seconds by not throwing away scaled and cropped images.

Cache cleaning

At work we use docker for our TYPO3 projects. Deploying changes to the live system only requires us to push into the main extension's master branch, and Jenkins will do the rest: Build the web server image with all the PHP code, pull that onto the production server, start up the new container, clear the cache and stop the old container.

Because potentially everything could have changed code-wise during deployments, we need to clear all the TYPO3 caches. Apart from the database cache tables, all files in typo3temp/ are pruned during deployment.

Responsive sites & focuspoint

Our TYPO3 projects have a responsive layout - it can be viewed in any resolution, and it will look good. Different resolutions and screen aspect ratios often need different images sizes and ratios - and those images need to be generated automatically.

To make sure that the important part of a picture is kept regardless of the targeted width-height-ratio, we utilize the focuspoint extension. Editors select the important part of the picture within the TYPO3 backend, and this part will be kept during image cropping.

Focus point selection

Mix that with different image resolutions for normal and high-density displays, and we're up to 6 images that need to be generated for a single image on the website (2 aspect ratios + 2 resolutions each).

When clearing typo3temp/, all those cropped and scaled images are thrown away and need to be regenerated. Calling pages with many images needed up to two minutes until they had all their images regenerated, which was just too much.

Processed files folder

Our goal was to keep the processed files. Their file names are a hash of the image processing configuration options, so they are stable over time. Cleaning caches has no effect on them.

Information about generated files are stored in the database as well, in table sys_file_processedfile. Since the database is kept during deployments, the contents of this table are also stable.

When re-using a production database dump on the test or dev system, TYPO3 notices if files have an entry in the processed files table but are missing on disk, and recreates them.


focuspoint saved the cropped files into typo3temp/focuscrop which was thrown away on deployments, so we made a patch to make that configurable.

With that in place we created a new folder in the site's document root, processed. It was "mounted" into TYPO3 with a new file storage record (uid: 2) that has its base path set to processed/ (path type "relative").

'processed' file storage settings Two file storages

The focuspoint extension was configured to store its generated files into processed/focuspoint

File storage fileadmin (auto-generated) was configured to store its "manipulated and temporary images" into

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

Raphael StoltKeeping your CLI integration tests green on Windows (25.3.2017, 18:50 UTC)
Lately on a Windows system, some failing integration tests for CLI commands utilising the Symfony Console component caused me some blip headaches by PHPUnit insisting that two strings are not identical due to different line endings. The following post documents the small steps I took to overcome these headaches.

First the assertion message produced by the failing test, see the console output below, got me thinking it might be caused by different encodings and line endings; though the project was utilising an .editorconfig from the early start and the related files were all encoded correctly and had the configured line endings. The Git configuration e.g. core.autocrlf=input also was as it should be.

1) Stolt\LeanPackage\Tests\Commands\InitCommandTest::createsExpectedDefaultLpvFile
Failed asserting that two strings are identical.
--- Expected
+++ Actual
@@ @@
#Warning: Strings contain different line endings!
-Created default 'C:\Users\stolt\AppData\Local\Temp\lpv\.lpv' file.
+Created default 'C:\Users\stolt\AppData\Local\Temp\lpv\.lpv' file.
Another deeper look at the CommandTester class yielded that it’s possible to disable the command output decoration and also to normalise the command output. So a change of the SUT preparation and a normalisation of the console output, visualised via a git diff -U10, brought the solution for this particular test.

diff --git a/tests/Commands/InitCommandTest.php b/tests/Commands/InitCommandTest.php
index 58e7114..fb406f3 100644
--- a/tests/Commands/InitCommandTest.php
+++ b/tests/Commands/InitCommandTest.php
@@ -48,21 +48,21 @@ class InitCommandTest extends TestCase
* @test
public function createsExpectedDefaultLpvFile()
$command = $this->application->find('init');
$commandTester = new CommandTester($command);
'command' => $command->getName(),
'directory' => WORKING_DIRECTORY,
- ]);
+ ], ['decorated' => false]);

// ommitted code

- $this->assertSame($expectedDisplay, $commandTester->getDisplay());
+ $this->assertSame($expectedDisplay, $commandTester->getDisplay(true));
$this->assertTrue($commandTester->getStatusCode() == 0);
Since the SUT had a lot of integration test for its CLI commands, the lazy me took the shortcut to extend the CommandTester and using it, with desired defaults set, instead of changing all of the related command instantiations.


namespace SUT\Tests;

use Symfony\Component\Console\Tester\CommandTester as ConsoleCommandTester;

class CommandTester extends ConsoleCommandTester
* Gets the display returned by the last execution of the command.
* @param bool $normalize Whether to normalize end of lines to \n or not
* @return string The display
public function getDisplay($normalize = true)
return parent::getDisplay($normalize);

* Executes the command.
* Available execution options:
* * interactive: Sets the input interactive flag
* * decorated: Sets the output decorated flag
* * verbosity: Sets the output verbosity flag
* @param array $input An array of command arguments and options
* @param array $options An array of execution options
* @return int The command exit code
public function execute(
array $input,
array $options = ['decorated' => false]
) {
return parent::execute($input, $options);
So it's a yay for green CLI command integration tests on Windows from here on. Another measure for the SUT would be to enable Continuous Integration on a Windows system via AppVeyor, but that’s a task for another commit 85bdf22.
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.

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