How to refactor code with PhpStorm

Matthew Setter demonstrates PhpStorm’s handy refactorings. Personally I use “extracting code to a new method” quite a lot.

Refactoring covers a range of different techniques, including moving, extracting, copying, deleting, and renaming. These cover all the types of changes which you are likely to make to your code on an ongoing basis.

Gladly, PhpStorm’s refactoring functionality, which is included as part of the core package, has support for all of these. In this tutorial, I’m going to step through a couple of them; specifically:

– Extracting code to a new method
– Renaming a function
– Changing a function’s signature

Varnish explained

Varnish is a piece of software that, amongst other things, can make your website much faster. In a new post on his blog, Mattias Geniar tells you all about it.

Varnish can do a lot of things, but it’s mostly known as a reverse HTTP proxy. It brands itself as an HTTP accelerator, making HTTP requests faster by caching them.

Varnish is usually associated with performance, but it greatly increases your options to scale your infrastructure (load balancing, failover backends etc) and adds a security layer right out of the box: you can easily let Varnish protect you from the httpoxy vulnerability or slowloris type attacks.

Be sure to watch Mattias’ excellent talk he gave at this years Laracon:

Top 5 programming fonts

Eric L. Barnes of Laravel-news and dotdev fame, did a little research on the most used fonts for programming.

Everyone has their ideal development setup, and many have spent countless hours customizing it to perfectly suit their needs. Outside of a color scheme, the next typical change is the font in use and every year new fonts are introduced giving us more to choose from than ever before.

To find out what everyone is using, I asked on Twitter and Facebook and had a ton of responses. Based on the answers here is a list of the top 5 programming fonts in use today

I’m a big fan of Fira Code myself. It has some nice ligatures and it just looks very good. Here it is in action in my IDE:


Method overloading is possible in PHP (sort of)

PHP does not support method overloading. In case you’ve never heard of method overloading, it means that the language can pick a method based on which parameters you’re using to call it. This is possible in many other programming languages like Java, C++.

So, under normal circumstances, you can’t do this in PHP:

class Foo
   function bar(A $baz)

   function bar(B $baz)

However, with some clever coding, Adam Wathan made a trait, aptly called Overloadable, that makes method overloading possible. It works by just accepting any parameters using the splat operator and then determining which of the given functions must be called according to the given parameters.

Let’s rewrite that example above using the Overloadable trait.

class Foo
    use Overloadable;

    function bar(...$arguments)
        return $this->overload($arguments, [
            function (A $baz) {
            function (B $baz) {

Pretty cool stuff. In a gist on GitHub Adam shares a couple of examples, the source code of the trait and the tests that go along with it. Check it out!

What’s in store for PHP performance?

Jani Tarvainen explains where PHP is heading performance-wise.

PHP 7.0 was a leap in performance that came with very easy adoption. Simply verify compatibility with the version and upgrade your server environment. Speeding up many older architecture apps like WordPress and Mediawiki by a factor of two is a testament to backwards compatibility.

In 7.1, the language runtime will continue to make modest improvements, but bigger gains will have to wait. One of these opportunities for a bigger improvement is the JIT implementation that is now bound for PHP 8.0

Understanding generated columns

in MySQL 5.7 generated columns were introduced. In the latest post on her blog Gabriela D’Ávila explains the feature.

There are two types of Generated Columns: Virtual and Stored.

Consider using virtual columns for data where changes happens in a significant number of times. The cost of a Virtual Column comes from reading a table constantly and the server has to compute every time what that column value will be. … You should consider using Stored Columns for when the data doesn’t change significantly or at all after creation,

If you like the post, be sure to check out Gabriela’s excellent talk at Laracon EU as well:

V2 of laravel-failed-job-monitor has been released

In the beginning of the year we released a package to notify you when a queued job in your Laravel application fails. Today we tagged v2 of that laravel-failed-job-monitor package. The big change is that it now uses Laravel 5.3’s native notification capabilities. So it’s a cinch to modify the notification or add some more channels.

Here’s how the notification looks like on Slack.

A big thank you to Egor Talantsev who helped out with this release. Take a look at the package on GitHub to learn more the package. Happy monitoring!

Taking PHP Seriously

Keith Adams, Chief Architect at Slack, gives some background on how PHP is used at his company.

Slack uses PHP for most of its server-side application logic, which is an unusual choice these days. Why did we choose to build a new project in this language? Should you?

Most programmers who have only casually used PHP know two things about it: that it is a bad language, which they would never use if given the choice; and that some of the most extraordinarily successful projects in history use it. This is not quite a contradiction, but it should make us curious. Did Facebook, Wikipedia, WordPress, Etsy, Baidu, Box, and more recently Slack all succeed in spite of using PHP? Would they all have been better off expressing their application in Ruby? Erlang? Haskell?

How I open sourced my way to my dream

Laravel employee #1, Mohammed Said, recently gave an interview at on his career and how he started with open source. Terrific story. A lot of what he says resonates with how I feel about working on open source.

Said believes many developers, in the Middle East and elsewhere, are interested in the open source community, but not sure how to get started: “They think they have to wait until they have something perfect.” That’s simply not the case, Said maintains. He encourages developers to dig deep into their favorite projects, especially into software they work with on a daily basis, and look for places they can offer “enhancements” to existing code.

Open source, he believes, is the best experience a developer can show in an interview. “Tech interviewers want one thing,” he says: “Show me your code.” You can share code you’ve written for your day job, but it’s probably impersonal or boring or even proprietary and closed source, so you can’t share it at all. Some code at work is done as part of a team and you can’t pick out what you did and what Jane down the hall did. Open source, on the other hand, is all you. It’s your passion, it’s publicly accessible, and it has your name on it.

Retain your SEO worth by correctly redirecting missing pages in a Laravel application

When transitioning from a old site to a new one the URLs of your site may change. If your old site was popular you probably want to retain your SEO worth. One way of doing this is by providing permanent redirects from your old URLs to your new URLs. Our new spatie/laravel-missing-page-redirector package makes that process very easy.

When installed the easiest way to add a permanent redirect is to just add it to the config file of the package. In the configured redirects you can use (optional) route parameters like you’re used to when specifying normal routes. Here’s an example.

return [

     * This is the class responsible for providing the URLs which must be redirected.
     * The only requirement for the redirector is that it needs to implement the
     * `Spatie\MissingPageRedirector\Redirector\Redirector`-interface
    'redirector' => \Spatie\MissingPageRedirector\Redirector\ConfigurationRedirector::class,

     * When using the `ConfigurationRedirector` you can specify the redirects in this array.
     * You can use Laravel's route parameters here.
    'redirects' => [
        '/non-existing-page' => '/existing-page',
        '/old-blog/{url}' => '/new-blog/{url}',
        '/old-section/{url?}' => '/new-section/{url}',

How does this work internally? Simple! If you’re application doesn’t return a 404 the package won’t to a thing. When your app does return a 404 we’ll first try to find a redirect for that request. If a redirect is found than that redirect is the result of the request.

To find the right redirect for a request and to leverage route parameters we’re instantiating a fresh router behind the scenes. The redirects are added to that router and then we’re dispatching the request on that router.

The package is also very extensible. In the config file you can specify a redirector that is responsible for providing the redirects. The default ConfigurationRedirector just reads the redirects for the config file itself. In our projects we want to let our clients specify the redirects, so we store the redirects in the database (and we’ve built some UI around that. Our DatabaseRedirector just gets its redirects from a Redirect model.

If you got tens of thousands of different redirects or if performance is a concern, you probably should manage the redirects at the webserver level. But if you’ve got only a couple of redirects using this package is definitely ok. Take a look at the package on GitHub to learn all the options. Head over to the list of Laravel packages on our company website to find out if we’ve made something that can be of use to you.

When are single-character variable names acceptable?

Generally I don’t like to abbreviate variable names. This answer on Quora lists a few situations where an abbreviation is probably ok.

There is a simple (but unsatisfying) answer to all questions of this form: they are acceptable when they would make the code clearer.

This can happen in a few ways. The most common, as you noted, is convention: i, j, k for loop variables, x and y for coordinates, e for exceptions, f and g for functions and so on.

Another is structure. Often, the broad structure of an expression is more important than its contents. Using shorter variable names makes it easier to read at a glance. I think this is often more important than being easy to read in detail!

If a variable has a very small scope—say one or two lines at most—and it’s easy to see where it comes from, having a long name is just noise.

A class to parse, build and manipulate URLs

For several projects and other packages we need to manipulate URL’s. Instead of coding the same URL class over and over again, we extracted URL manipulation to it’s own package. Here are some code examples on how you can use it.

$url = Url::fromString('');

echo $url->withHost('')->withPath('spatie');
// ''

Query parameters can be retrieved and transformed:

$url = Url::fromString('');

echo $url->getQuery(); // 'utm_source=github&utm_campaign=pacakges'
echo $url->getQueryParameter('utm_source'); // 'github'
echo $url->withoutQueryParameter('utm_campaign'); // ''

It can retrieve path segments:

$url = Url::fromString('');

echo $url->getSegment(1); // 'opensource'
echo $url->getSegment(2); // 'laravel'

It implements PSR-7’s UriInterface interface:

class Url implements UriInterface { /* ... */ }

The league/uri is a more powerful package than this one. The main reason our package exists, is because the alternatives require non-standard php extensions. If you’re dealing with special character encodings or need bulletproof validation, you’re definitely better off using league/uri.

That being said, if you need a lightweight solution, take a look at spatie/url on Github.

Managing opening hours with PHP

For several different clients we needed to display a schedule of opening hours on their websites. They also wanted to display if a department / store / … is open on the moment you visit the site. My colleague Seb extracted all the functionality around opening hours to the newly released opening-hours package.

You create an OpeningHours object that describes a business’ opening hours. It can be queried for open or closed on days or specific dates, or use to present the times per day.

A set of opening hours is created by passing in a regular schedule, and a list of exceptions.

$openingHours = OpeningHours::create([
    'monday' => ['09:00-12:00', '13:00-18:00'],
    'tuesday' => ['09:00-12:00', '13:00-18:00'],
    'wednesday' => ['09:00-12:00'],
    'thursday' => ['09:00-12:00', '13:00-18:00'],
    'friday' => ['09:00-12:00', '13:00-20:00'],
    'saturday' => ['09:00-12:00', '13:00-16:00'],
    'sunday' => [],
    'exceptions' => [
        '2016-11-11' => ['09:00-12:00'],
        '2016-12-25' => [],

The object can be queried for a day in the week, which will return a result based on the regular schedule:

// Open on Mondays:
$openingHours->isOpenOn('monday'); // true

// Closed on Sundays:
$openingHours->isOpenOn('sunday'); // false

It can also be queried for a specific date and time:

// Closed because it's after hours:
$openingHours->isOpenAt(new DateTime('2016-09-26 19:00:00')); // false

// Closed because Christmas was set as an exception
$openingHours->isOpenAt(new DateTime('2016-12-25')); // false

It can also return arrays of opening hours for a week or a day:

// OpeningHoursForDay object for the regular schedule

// OpeningHoursForDay[] for the regular schedule, keyed by day name

// OpeningHoursForDay object for a specific day
$openingHours->forDate(new DateTime('2016-12-25'));

// OpeningHoursForDay[] of all exceptions, keyed by date

Take a look at the package on GitHub to learn the full api. Check out the list of PHP packages we’ve previously made to see if we’ve made something else that could be of use to you.

A Laravel package to store language lines in the database

In a vanilla Laravel installation you can use language files to localize your app. The Laravel documentation refers to any string in a language file as a language line. You can fetch the value of any language line easily with Laravel’s handy trans-function.

trans('messages.welcome'); // fetches the string in the welcome-key of the messages-lang-file.

In our projects a client sometimes wants to change the value of such a language line. But as we don’t want to let the client edit php files we had to come up with another way of storing localized strings.

Our new laravel-translation-loader package will enable the language lines to be stored in the database. In this way you can build a GUI around that to let the client manipulate the values. When using our package can still use all the features of the trans function you know and love.

Once the package is installed you’ll have a language_lines table where all localized values can be stored. There’s a LanguageLine model included. Here’s how you can create a new LanguageLine:

use Spatie\TranslationLoader\LanguageLine;

   'group' => 'validation',
   'key' => 'required',
   'text' => ['en' => 'This is a required field', 'nl' => 'Dit is een verplicht veld'],

The cool thing is that that can still keep using the default language files as well. If a requested translation is present in both the database and the language files, the database version will be returned by the trans function.

While creating the package we also kept an eye on performance. When requesting a language line from a group we will retrieve all language lines from a group. In this way we avoid a separate query from each language line. We’ll also cache the whole group to avoid querying the database from language lines in subsequent requests. Whenever a language line in a group is created, updated or deleted, we’ll invalidate the cache of the group.

The package is also easy to extend. Image you want to store your translations not in a php-files or the database, but in a yaml-file or csv-file or… you can create your own translation provider.

A translation provider can be any class that implements the Spatie\TranslationLoader\TranslationLoaders\TranslationLoader-interface. It contains only one method:

namespace Spatie\TranslationLoader\TranslationLoaders;

interface TranslationLoader
     * Returns all translations for the given locale and group.
    public function loadTranslations(string $locale, string $group): array;

Translation providers can be registered in the translation_loaders key of the config file.

Take a look at the readme of the package on GitHub to learn all the options. Be sure to also check out the list of Laravel packages our team has previously made.

A better dd() for your TDD

On the Tighten blog Keith Damiani wrote an article how you can mold the dd helper to your liking.

An important part of every Laravel developer’s debugging arsenal is the humble dd() helper function—”dump and die”—to output the contents of a variable and terminate execution of your code. In the browser, dd() results in a structured, easy-to-read tree, complete with little arrow buttons that can be clicked to expand or hide children of nested structures. In the terminal, however, it’s a different story.

Fortunately, it’s simple to build your very own customized version of dd() to help tame your unwieldly terminal output.

Game & Watch LCD Donkey Kong recreated with HTML and CSS

James Holderness recreated the Donkey Kong Game & Watch without JavaScript. Amazing work.

There are two things I’ve always wanted to try in HTML: generating a photorealistic image using CSS, and creating an interactive game without the need for JavaScript. HTML Kong is the end result of those two ambitions – a reproduction of the Game & Watch video game, Donkey Kong, using just HTML and CSS.

For those of you that haven’t heard of it, Game & Watch was a line of LCD handheld video games from the 1980s. The Donkey Kong title was probably one of the most popular in the series, selling more than a million units worldwide. The game was split over two screens and built into a distinctive clamshell casing.

If you want to skip reading the making of and go straight to the game, click here.

The Laracon EU 2016 videos are now available

This year’s Laracon EU was an amazing conference. The venue was astonishing, there were lots of cool talks and interesting people to talk to. If you’re using Laravel or PHP going to this conference really is a no brainer.

If you were unable to attend or want to see the talk you missed during the conference you can now do so. The organisers have uploaded video’s of all talks to their YouTube channel.

I had the honor speaking there as well. My talk was about managing backups with Laravel. Here’s the video of my first ever conference talk:

At one point during my talk I show this slide on future plans for the package:screen-shot-2016-10-07-at-10-04-54

I’m proud to say that all that work is already done: version 3 of laravel-backup was made Laravel 5.3 compatible. Version 4 of the package uses Laravel 5.3’s native notifications and uses PHP 7 features to keep the code clear. The db-dumper package, which is used under the hood, was rewritten and is now easier to use.

I’ll definitely go to the next Laracon EU conference and hope to see you there too.

A Sequel Pro bundle to generate Laravel migration files

Colin Viebrock, author of the well know laravel-sluggable package, created a new Sequel Pro bundle that can genenerate Laravel migration files.

Connect to a database, and select a table in the left-hand column. From the application menu, choose Bundles › Export › Export to Laravel Migration. The resulting Laravel migration file will be saved to your desktop. You can then move this file into your Laravel project (usually /database/migrations) and then run artisan migrate.