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

Benjamin Eberlei:
Explicit Global State with Context Objects
Mar 24, 2017 @ 11:50:12

In a post to his site Benjamin Eberlei looks at global state in PHP using something called "context objects" and how they can be used as an alternative to true global state.

Global State is considered bad for maintainability of software. Side effects on global state can cause a very nasty class of bugs. Context objects are one flavour of global state. For example, I remember that Symfony1 had a particularly nasty context object that was a global singleton containing references to very many services of the framework.

As with every concept in programming, there are no absolute truths though and there are many use-cases where context objects make sense. This blog posts tries to explain my reasons for using context objects.

He starts by getting everyone on the same page by defining a context - the "circumstances in which something can be fully understood". He then moves into the world of context objects, talking about how they encapsulate the information other objects need to execute. They're essentially "container" objects that allow for more control that something like the normal PHP superglobals. From there he helps you define what kind of context objects you might need in your application and provides a real-world example from his own experience at Tideways.

tagged: global state context object tutorial introduction definition

Link: https://beberlei.de/2017/03/12/explicit_global_state_with_context_objects.html

SitePoint PHP Blog:
Parallel Programming with Pthreads in PHP – the Fundamentals
Mar 24, 2017 @ 10:40:07

The SitePoint PHP blog has posted a tutorial that introduces some of the fundamentals of parallel programming in PHP. In their examples they make use of the pthreads extension to help bring simpler parallel programming to the language (otherwise you'd have to do odd things with shell commands and foreground/background controls).

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.

Despite the article being about the use of pthreads, it starts out talking about when not to use it, possibly saving you some time in the long run. With that out of the way it then starts in on the handling of "on-off tasks" with an example of fetching the "title" value from Google.com. This is then enhanced showing how to use the "Threaded" base class to define other classes that can be used inside of threads. The article moves on covering other topics including:

  • recycling threads
  • pthreads and (im)mutability
  • synchronization of threads

Each item in the list comes with plenty of example code showing you how to create the classes that execute the threads and the output they should generate.

tagged: parallel programming fundamentals tutorial introduction pthreads extension

Link: https://www.sitepoint.com/parallel-programming-pthreads-php-fundamentals/

Zend Framework Blog:
Error Handling in Expressive
Mar 24, 2017 @ 09:30:31

The Zend Framework blog has a new tutorial posted by Matthew Weier O'Phinney covering error handling techniques in Expressive with a few examples making use of some custom middleware and logic.

One of the big improvements in Expressive 2 is how error handling is approached. While the error handling documentation covers the feature in detail, more examples are never a bad thing!

In their example they're creating an API resource that returns a list of book details (ones the user has read). The goal is to use the existing error handling for everything except the custom exceptions they want to throw but keep with the JSON handling throughout. First the middleware to handling the API request is shown, complete with sorting and pagination. Then come the custom exception examples for invalid requests and server issues. These exceptions are then put into the Problem Details format with the help of another middleware. This then all tied together with the nested middleware handling Expressive provides and an example of the end result is included.

tagged: error handling expressive custom problemdetails tutorial json middleware

Link: https://framework.zend.com/blog/2017-03-23-expressive-error-handling.html

TutsPlus.com:
Building With the Twitter API: Creating Friends to Follow
Mar 23, 2017 @ 12:32:04

The TutsPlus.com site has posted the latest tutorial in their "Building with the Twitter API" series showing how to, in a Yii2 application, automatically add friends to a Twitter account via the Twitter API. You've probably seen this in several services that offer suggestions of followers to add to your list.

Today I'll guide you through using the Yii2 Framework for PHP to access the Twitter API and automate adding friends to people's Twitter accounts. (If you'd like to learn more about Yii2, check out our parallel series Programming With Yii2.)

And, I've created a website, Twixxr.com, which will let you demonstrate the feature by adding prominent women on Twitter for your account to follow.

The tutorial starts with links to some of the other Twitter tutorials that have been posted in the past and how things have evolved to make it easier in a Yii2 application. He starts by helping you get the Twitter OAuth PHP Library installed and lists some of the goals of the end result. The code is included to authorize the user and handle the callback once they've approved the app in the normal OAuth flow. It then shows how to connect via the API using that user's information, load profiles for the suggested users and link them as a friend. The tutorial finishes with a look at performance and a bit of code used to handle the backend processing of the request instead of performing it in real time.

tagged: twitter tutorial api oauth2 friends follow suggestion yii2

Link: https://code.tutsplus.com/tutorials/building-with-the-twitter-api-creating-friends-to-follow--cms-27492

PhpStorm Blog:
Working With PHPUnit and PhpStorm
Mar 23, 2017 @ 11:50:12

On the PhpStorm blog (from JetBrains) Gary Hockin reflects on a post from Adam Wathan with tips for combining PHPUnit and PhpStorm for more effective debugging.

Community stalwart and Laravel aficionado Adam Wathan blogged on his PHPUnit workflow in Sublime text.

Gary then goes through the points in Adam's post and shows how they can (mostly) be accomplished directly in PhpStorm:

  • Generating unit test boilerplate for a class
  • Using "snippets" to create shortcuts for reusable code
  • Running the tests in just one file directly from the IDE

Each section comes with a brief description and animated screen grabs showing the flow of the setup and use for each.

tagged: phpstorm debugging unittest feature generation snippets singlefile tutorial

Link: https://blog.jetbrains.com/phpstorm/2017/01/working-with-phpunit-and-phpstorm/

Robert Basic:
Loading fixtures for a Symfony app in Behat tests
Mar 23, 2017 @ 10:38:58

Robert Basic has a new post to his site with some advice for the Behat users out there testing their Symfony applications. He shows how to easily load up fixture data with the help of Doctrine.

Performing end to end testing of any application requires from us to have a set of reliable test data in the database.

If we write a Symfony application and use Behat to do the end to end testing, the we can use the Doctrine fixtures bundle to create the required fixture loaders and load them in our Behat scenarios when required.

He walks you through the installation of the Doctrine fixtures bundle (via Composer, naturally) and how to enable it via the Symfony kernel configuration. He then includes an example of the fixture loader class from the FOSUserBundle and how it works. Next up is the installation of the Behat Symfony 2 extension and a bit of extra code to make a new feature context for Behat containing a "loadDataFixtures" method to do the heavy lifting.

tagged: fixture symfony application behat load extension bundle tutorial

Link: https://robertbasic.com/blog/loading-fixtures-for-a-symfony-app-in-behat-tests/

Stefan Koopmanschap:
Sculpin and Docker
Mar 22, 2017 @ 12:49:05

Stefan Koopmanschap has written up a tutorial on his site introducing the use of Docker and Sculpin to create an easily reproducible and manageable blogging setup.

I've been running this blog on Sculpin for quite a while now, and I'm quite happy with how that works. We've been in a process of migrating some of our websites off a standard VPS towards a setup with Docker, Gitlab CI and Rancher. I've now migrated some websites, which is relatively easy, but most of those sites were dynamic PHP websites. Migrating a site that generates static HTML and running that is a slightly different thing. Here's how I ended up doing it.

First he covers his old setup - essentially the manual run of a shell command to generate the latest version of a the static Sculpin site. He decided to update the process and help makes things more automatic using Docker and a Gitlab pipeline flow. He then documents his attempts and configuration options as he built up the Docker configuration he wanted. This ultimately resulted in a Docker setup that installed PHP and Nginx to serve up the site, Composer to load in the required dependencies (like Sculpin) and the commands to "deploy" the latest version of the site publicly.

tagged: sculpin docker setup configuration tutorial dockerfile php7

Link: https://leftontheweb.com/blog/2017/03/18/sculpin-and-docker/

Simon Holywell:
PHP and immutability
Mar 22, 2017 @ 11:21:37

In a recent post to his site Simon Holywell covers immutability in PHP. PHP, by default, uses weak typing and doesn't support much in the way of immutability but Simon shows you a few ways you can get around this and make immutable objects you can use and extend.

Being a weakly typed dynamic language, PHP has not really had the concept of immutability built into it. We’ve seen the venerable define() and CONSTANTS of course, but they’re limited. Whilst PHP does ship with an immutable class as part of it’s standard library, DateTimeImmutable, there is no immediately obvious method to create custom immutable objects.

[...] It is possible to write your own immutables using some simple and sneaky PHP techniques though. We’re going to use a simplistic data requirement to make the examples in this article easier to follow. I’ll be using professional skateboarders and the tricks that they brought to the world.

He starts the article talking about immutability and how it relates back to the current (as of PHP 7) values supported in constants - scalars and arrays (no objects). He then starts on the code to create the base Immutable class that sets its values via the constructor. He then points out some of the common "work arounds" people use when trying to work with immutable objects and some techniques to help prevent it: the use of final, a "flag" preventing another constructor call, etc.

tagged: immutable tutorial technique php7 constant

Link: https://www.simonholywell.com/post/2017/03/php-and-immutability/

QaFoo:
How to Perform Extract Service Refactoring When You Don't Have Tests
Mar 22, 2017 @ 10:42:39

On the QaFoo blog they've posted an article sharing advice about refactoring to extract logic to services when there's no testing to cover the code.

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. This post presents a list of steps and checklists to perform extract service when you don't have tests or only minimal test coverage. It is not 100% safe but it provides small baby-steps that can be applied and immediately verified.

The article talks about some of the primary risks when performing this kind of refactoring and how their extract method recommendations could case some of those issues. The tutorial then breaks down the process into the small steps:

  • Step 1: Create Class and Copy Method
  • Step 2: Fix Visibility, Namespace, Use and Autoloading
  • Step 3: Check for Instance Variable Usage
  • Step 4: Use New Class Inline
  • Step 5: Inline Method
  • Step 6: Move Instantiation into Constructor or Setter
  • Step 7: Cleanup Dependency Injection

While that seems like a lot of steps to take, they're all pretty small. They include a series of code snippets giving you an example to work from, making these small steps to refactor current functionality into a Solr service class.

tagged: tutorial refactor extract service tutorial unittest example code

Link: https://qafoo.com/blog/099_extract_service_class.html

QaFoo:
How to Perform Extract Service Refactoring When You Don't Have Tests
Mar 22, 2017 @ 10:42:39

On the QaFoo blog they've posted an article sharing advice about refactoring to extract logic to services when there's no testing to cover the code.

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. This post presents a list of steps and checklists to perform extract service when you don't have tests or only minimal test coverage. It is not 100% safe but it provides small baby-steps that can be applied and immediately verified.

The article talks about some of the primary risks when performing this kind of refactoring and how their extract method recommendations could case some of those issues. The tutorial then breaks down the process into the small steps:

  • Step 1: Create Class and Copy Method
  • Step 2: Fix Visibility, Namespace, Use and Autoloading
  • Step 3: Check for Instance Variable Usage
  • Step 4: Use New Class Inline
  • Step 5: Inline Method
  • Step 6: Move Instantiation into Constructor or Setter
  • Step 7: Cleanup Dependency Injection

While that seems like a lot of steps to take, they're all pretty small. They include a series of code snippets giving you an example to work from, making these small steps to refactor current functionality into a Solr service class.

tagged: tutorial refactor extract service tutorial unittest example code

Link: https://qafoo.com/blog/099_extract_service_class.html