Expressive Code & Real Time Facades

In a new post on his blog Taylor Otwell gives a nice example on how real time facades can make code more testable.

Recently, I worked on some code that surfaced my most common use-case for Laravel 5.4’s “real-time” facades. If you’re not familiar with this feature, it allows you to use any of your application’s classes as a Laravel “facade” on-demand by prefixingFacades to the namespace when importing the class. This is not a feature that is littered throughout my code, but I find it occasionally provides a clean, testable approach to writing expressive object APIs.

https:[email protected]/expressive-code-real-time-facades-41c442914291

PHP Versions Stats – 2017.1 Edition

Jordi Boggiano, co-creator of Composer / Packages, published some new stats on the usage of PHP versions. Great to see that PHP 7 overall now represents over 50%.

A quick note on methodology, because all these stats are imperfect as they just sample some subset of the PHP user base. I look in the packagist.org logs of the last month for Composer installs done by someone. Composer sends the PHP version it is running with in its User-Agent header, so I can use that to see which PHP versions people are using Composer with.

https://seld.be/notes/php-versions-stats-2017-1-edition

Conditionally pushing event listeners to queue

Mohammed Said, Laravel employee #1 and diver, explains how you can avoid pushing unnecessary jobs to a queue.

How many customers will reach the 10K purchase milestone? does it make sense to push a Job to queue for every single purchase while there’s a huge chance that this job will just do nothing at all? IMHO this is a waste of resources, you might end up filling your queue with thousands of unnecessary jobs.

It might be a good thing if we can check for that condition before queueing the listener.

http://themsaid.com/conditionally-queue-listeners-laravel-20170505/

Using Guzzle 6 Middleware in a Laravel Application

Paul Redmond explains how you can use Guzzle 6′ middleware to add a HMAC authorization header.

I prefer to keep my dependencies as up-to-date as possible so I decided to learn Guzzle 6 and become more familiar with the middleware. The concepts are pretty straightforward and I have a few patterns that I like to use when building out middleware within my Laravel applications.

https:[email protected]/using-guzzle-6-middleware-in-a-laravel-application-7fbd6d966235

Manage permission and roles in a Laravel app

A few week ago we released a new major version of laravel-permission. This package makes it easy to store permission and roles in the database. Our package plays nice with Laravel’s Gate and has support for multiple guards.

In a new post on his blog Saqueib Ansari shows how you can create an interface to assign permissions and roles to a user using our package.

Laravel comes with Authentication and Authorization out of the box, I have implemented many role and permissions based system in the past, using laravel, it’s peace of cake. In this post, we are going to implement a fully working and extensible roles and permissions on laravel 5.4. When we finish we will have a starter kit which we can use for our any future project which needs roles and permissions based access control.

http://www.qcode.in/easy-roles-and-permissions-in-laravel-5-4

Think you know the top web browsers?

Peter O’Shaughnessy, a developer advocate for Samsung, explains that your idea on which browsers are the most popular is probably wrong.

Our traditional idea of the top five browsers may be over-simplified, outdated and skewed.

Chrome, Firefox, Safari, IE/Edge, Opera… It is a common idea that these are the five “major browsers”. Our familiarity with them is comforting, but it might be a skewed and outdated view. Partly from our Western bubble and partly a hangover from the days of desktop dominance.
Let’s take a look at some numbers so we can better represent the reality.

https://medium.com/samsung-internet-dev/think-you-know-the-top-web-browsers-458a0a070175

Moving from PHP (Laravel) to Go

Danny Van Kooten did an interesting experiment. He completely rewrote an Laravel app to a version in Go. In a post on his blog he shares some details about his project along with some benchmarks.

Earlier this year, I made an arguably bad business decision. I decided to rewrite the Laravel application powering Boxzilla in Go.

No regrets though.

Just a few weeks later I was deploying the Go application. Building it was the most fun I had in months, I learned a ton and the end result is a huge improvement over the old application. Better performance, easier deployments and higher test coverage.

https://dannyvankooten.com/laravel-to-golang/

Familiarity Bias is Holding You Back: It’s Time to Embrace Arrow Functions

I don’t think that less lines of code automatically means code is more readable, but I’m a big fan of ES6′ arrow functions. In this article Eric Elliott dives deep into them.

I also supect that your team would become significantly more productive if you learned to embrace and favor more of the concise syntax available in ES6.
While it’s true that sometimes things are easier to understand if they’re made explicit, it’s also true that as a general rule, less code is better.
If less code can accomplish the same thing and communicate more, without sacrificing any meaning, it’s objectively better.

https://medium.com/javascript-scene/familiarity-bias-is-holding-you-back-its-time-to-embrace-arrow-functions-3d37e1a9bb75

Let’s hope we’ll soon have array functions in PHP too.

Dropbox will turn off v1 of their API soon. It’s time to update your PHP application.

Last year on 28th of June Dropbox deprecated v1 of their API. On the same date this year they will turn off all v1 endpoints. If you’re using using Flysystem, Laravel or the official PHP SDK to work with Dropbox, it’s the time to update.

Last week my company released a Dropbox API client and a Flysystem Dropbox adapter that both use v2 of the dropbox API. In this blogpost I’d like to explain how to install and use these packages.

Updating Flysytem adapters

Flysystem is an awesome package created by Frank de Jonge that abstracts filesystems. It provides a common API for all kinds of filesystems. So you can use the same API to work with S3, Dropbox, Sftp servers and whatnot. Until recently Flysystem suggested to use their home cooked Dropbox adapter. That driver only supports v1 of the Dropbox API. Therefore will stop working after 28th of June of this year. If your project uses that adapter you can very easily swap it with our new Dropbox adapter.

This is how you newed up the old adapter:

use League\Flysystem\Dropbox\DropboxAdapter;
use League\Flysystem\Filesystem;
use Dropbox\Client;

$client = new Client($accessToken, $appSecret);
$adapter = new DropboxAdapter($client);

$filesystem = new Filesystem($adapter);

This is how you should new up the new adapter (after having run composer require spatie/flysystem-dropbox.

use League\Flysystem\Filesystem;
use Spatie\Dropbox\Client;
use Spatie\FlysystemDropbox\DropboxAdapter;

$client = new Client($authorizationToken);

$adapter = new DropboxAdapter($client);

$filesystem = new Filesystem($adapter);

Notice that instead of an accessToken and an appSecret you now need a authorizationToken. Luckily Dropbox has made this very easy. You can just generate a token in the App Console for any Dropbox API app. You’ll find more info at the Dropbox Developer Blog.

Updating Laravel applications

Laravel comes with filesystem abstraction out of the box. Under the hood it’s powered by Flysystem. So if you’re currently using a Dropbox disk in Laravel you also have a bit of work to upgrade. In order to make use of Dropbox disk you had to create a service provider not unlike this one (example taken from the old Laravel docs):

namespace App\Providers;

use Storage;
use League\Flysystem\Filesystem;
use Dropbox\Client as DropboxClient;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Dropbox\DropboxAdapter;

class DropboxServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        Storage::extend('dropbox', function ($app, $config) {
            $client = new DropboxClient(
                $config['accessToken'], $config['clientIdentifier']
            );

            return new Filesystem(new DropboxAdapter($client));
        });
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

To upgrade simply pull in our Dropbox adapter by running composer require spatie/flysystem-dropbox. Next you must update your service provider.

namespace App\Providers;

use Storage;
use League\Flysystem\Filesystem;
use Spatie\Dropbox\Client as DropboxClient;
use Illuminate\Support\ServiceProvider;
use Spatie\FlysystemDropbox\DropboxAdapter;

class DropboxServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        Storage::extend('dropbox', function ($app, $config) {
            $client = new DropboxClient(
                $config['authorizationToken']
            );

            return new Filesystem(new DropboxAdapter($client));
        });
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Like mentioned above you can generate authorization token on the App Console at Dropbox.

And with your Laravel application makes use of Dropbox API v2.

Updating other applications

If your application uses the old Dropbox PHP SDK you’ll be sad to learn that there currently are no plans to release and official PHP SDK for v2.

But you have a few options to upgrade. You could opt to use our dropbox-api package. It currently only support the methods needed by our Flysystem dropbox adapter, but we’re open for PRs that add more methods to the package.

Alternativly you could use the Dropbox package by Kunal Varma or the Dropbox SDK made by Alorel, but both don’t have stable releases just yet.

In closing

If you’re using Dropbox in your application be sure to verify that you’re using v2 of the API. Still on v1? Then be sure to upgrade before 28th of July to avoid tears or worse. Our Flysystem adapter and API package can help out.

These packages are not the first ones my company has released. Be sure to check out this pile of packages we’ve previously released.

A practical introduction to snapshot testing

While working a little bit on laravel-sitemap I decided to refactor the tests to make use of our own snapshot assertions package. The snapshot package enables you to generate snapshots with the output of your tests. On subsequent runs of those tests it can assert if the output still matches the contents of the snapshot.

In this video I demonstrate how the refactor of the tests of laravel-sitemap was done. (double-click on it to view it full-screen)

If you want to know more about snapshot testing, then read this blog post written by my colleague Sebastian. The refactor of the tests can be viewed in this commit on GitHub.

(Little note on the video itself: this is my first tutorial video I ever made. After recording it I noticed that I used a wrong ratio resulting in those black bars on the side. Ah well, you live you learn. Next time it will be better. For those interested, I used a Blue Yeti Pro mic to record my voice and ScreenFlow to record and edit the video.)

$PHP = 💩;

Simon Yousoufov argues that PHP is going the way of the dodo.

It’s well known that PHP is a dead programming language and that its 22-year-old ecosystem is effectively useless now that we have Node and its fancy new asynchronous frameworks. Node’s superiority is evident because everyone knows that single-threaded, asynchronous, programs are better by default. Faster. Stronger, even.

https://medium.com/fuzz/php-a0d0b1d365d8

Building a desktop application with Electron

Electron is a library that enables you to create desktop apps with JavaScript, Html and css. If you’re interesting in playing around with this cool technology check out this tutorial by Kristian Poslek.

In this article, I’ll try to guide you through the process of building a simple desktop application and touch on important concepts for building desktop application with JavaScript.

https://medium.com/developers-writing/building-a-desktop-application-with-electron-204203eeb658

Together with Marcel Pociot and the help of Alex Vanderbist I’m currently building my first Electron app. It’s a bit too early to share any details about it except that we’ll open source it (and it’ll be free).

A conversation on laravel-html

Hi, how are you?
I’m fine thanks! How are you?

I saw you released another package last week.
Yup yup, you mean laravel-html, right? It was actually coded up by my colleague Sebastian, who did an awesome job.

But why put out yet another html generator? Html generation is a solved problem, right?
Yes, it is but…

I’m mean we already have laravelCollective/html
Yes, but…

Why not just type html, … come on, do we really need a package for this? It’s easy to just type html.
Let me say first that if you’re happy with your current solution, just stick with it. There’s no right or wrong here. Because everybody already has their own favourite solution, html generation is a pretty divisive subject. I believe that’s why html generation was kicked out of the Laravel core.

Stop rambling, just tell why you’ve created this.
Well, like probably most fellow artisans we have been using the laravel collective package for quite some time and we were quite happy with it. Since html generation got kicked out of the Laravel core and has been put in the laravel collective package it has not evolved much. Take for instance this piece of code:

Form::email('element-name', null, ['class' => 'my-class']);

Seems like this is quite simple solution, but a few things bother me. That null parameter for instance when there is no value. And the fact that you need pass an array as the third parameter. In our package all html can be built up with a fluent interface. So you can do this:

html()->email('element-name')->class('my-class');

Yeah ok, that’s certainly nice, but do you plan to code all of your html like this?
No, certainly not. For simple things I prefer just writing the html. But when it comes to generating forms, I prefer using our package. Because when typing forms manually there’s so much things to you need to take care of: the method field, the csrf token field etc… it’s very error prone.

Here’s how you can create a form with laravel-html:

html()->form('PUT', '/post')->open();
html()->email('email')->placeholder('Your e-mail address');
html()->submit('Process this');
html()->form()->close();

That’ll output:

<form method="POST" action="/post">
    <input type="hidden" name="_method" id="_method" value="PUT">
    <input type="hidden" name="_token" id="_token" value="csrf_token_will_be_here">
    <input type="email" name="email" id="email" placeholder="Your e-mail address">
    <input type="submit" value="Process this">"
</form>

As you can see those hidden _method and _token fields were added automatically.

Cool!
You can also use models or anything that implements ArrayAccess really to prefil the values of the form.

html()->model($user);

html()->input('name');

So if name is set on user the form element will receive it’s value.

<input type="text" name="name" id="name" value="John">

This all sounds interesting, please continue.
Well, if you want to know more, you really should really check out the documentation. It contains all you need to know. If you have a question about the package feel free to open up an issue at GitHub.

Is there anything more that we should know about the package?
It’s PHP 7.1 only.

Wut? Can you create a PHP 7.0 or PHP 5.6 version?
Boring. Next question.

But why did you make it PHP 7.1 only? My projects do not use that version yet.
We mainly create packages to use them in our own projects. All our new client projects use PHP 7.1, so it makes no sense for us to create packages for an older version of PHP.

But PHP 7.0 is still an active version…
I really don’t care. You’re of course free to fork the package and maintain your own copy that’s compatible with an older PHP version. Yay for open source.

Ok, I’ll go check it out!
Please do, like already mentioned the docs are here. And be sure to take a look at the other packages we’ve created previously.

Stay up to speed with PHP by reading these feeds

In the PHP ecosystem we’re blessed with so many people blogging about their favourite language. Everyday new interesting content on PHP gets posted somewhere on the web.

Visiting each blog separately to see if new content has been posted is quite tedious. Luckily this problem has been solved long ago by RSS feeds. Almost every interesting blog has a feed where you can easily subscribe to with one of the many RSS readers out there.

Over the years I’ve built up quite a collection of feeds to PHP related blogs. So why not share those feeds? I’ve exported all my feeds to a gist on GitHub.

https://gist.github.com/freekmurze/b7f78708697266d507311a6e800eaeae

This file can be imported by nearly all RSS readers.

If you’re looking for a good RSS reader on macOS then I can wholeheartedly recommend Reeder. It’ll cost you a few bucks, but it’s certainly worth it. Reeder needs an RSS account to sync with. Personally I prefer Feedly, which is free.

Have fun reading all these blogs. If I’ve missed a good blog on PHP, let me know in the comments below.

Free Wildcard SSL Using Forge + Cloudflare

If you need a free SSL certificate Let’s Encrypt seems like the obvious way to go. But the installation and renewal process of Let’s Encrypt surely has it’s caveats. An alternative to Let’s Encrypt is to use a free certificate issued by Cloudflare. On his blog Taylor Otwell published a post explaining how to request and install such a certificate.

I personally prefer to use Cloudflare, another service that offers free SSL certificates, as well as a variety of other free and paid services that are useful for web developers. I prefer Cloudflare because:
– Cloudflare doesn’t require any renewal process to ever run on my server. LetsEncrypt renewals must run on my server at least every 3 months and that’s just one more thing that sometimes can (and does) go wrong.
– Cloudflare supports wildcard sub-domains.

https:[email protected]/free-wildcard-ssl-using-forge-cloudflare-ab0ebfbf129f

Tweaking Eloquent relations – how to get latest related model?

Jarek Tkaczyk demonstrates how you can use a helper relation to eager load specific models.

Have you ever needed to show only single related model from the hasMany relationship on a set of parents?

Being it latest, highest or just random, it’s not very clever to load whole collection using eager loading, just like running query per every parent.

Of course you can do that better, and now let me show you how.

https://softonsofa.com/tweaking-eloquent-relations-how-to-get-latest-related-model/

A package for snapshot testing in PHPUnit

My colleague Sebastian recently released a new package called phpunit-snapshot-assertions. In a new post on his blog he tells all about it.

The gist of snapshot testing is asserting that a set of data hasn’t changed compared to a previous version, which is a snapshot of the data, to prevent regressions. The difference between a classic assertEquals and an assertMatchesSnapshot is that you don’t write the expectation yourself when snapshot testing. When a snapshot assertion happens for the first time, it creates a snapshot file with the actual output, and marks the test as incomplete. Every subsequent run will compare the output with the existing snapshot file to check for regressions.

https:[email protected]/a-package-for-snapshot-testing-in-phpunit-2e4558c07fe3