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

How to set up your Laravel application for zero-downtime deploys

On his blog Matt Stauffer published a new post explaining the steps required to deploy your app without any downtime.

The reason you’re getting zero-downtime deploy from these tools is because the entire deploy process—clone, composer install, etc.—doesn’t happen in the directory that is currently serving your site. Instead, each new release gets its own separate “release” directory, all while your site is still being served from its current “release” directory.

https://mattstauffer.co/blog/how-to-set-up-your-laravel-application-for-zero-downtime-envoyer-capistrano-deploys

In my own projects I handle these capistrano like deploys using a custom Envoy script:
https://github.com/spatie/blender/blob/master/Envoy.blade.php

Six reasons why JavaScript’s async/await blows promises away

In the JavaScript world promises are a great way to deal with stuff that needs to happen asynchronously. But there’s also another new way to go about it: async/await.

In case you missed it, Node now supports async/await out of the box since version 7.6. If you haven’t tried it yet, here are a bunch of reasons with examples why you should adopt it immediately and never look back.

For those who have never heard of this topic before, here’s a quick intro
– Async/await is a new way to write asynchronous code. Previous options for asynchronous code are callbacks and promises.
– Async/await is actually built on top of promises. It cannot be used with plain callbacks or node callbacks.
– Async/await is, like promises, non blocking.
– Async/await makes asynchronous code look and behave a little more like synchronous code. This is where all its power lies.

https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9

Creating strictly typed arrays and collections in PHP

You might thing that PHP is not able to automatically perform a type check on items in an array. But using variadic constructor this is possible. Bert Ramakers wrote a blogpost with some good examples on how to do this.

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.

https://medium.com/2dotstwice-connecting-the-dots/creating-strictly-typed-arrays-and-collections-in-php-37036718c921

Partial model updates in Laravel

Michael Dyrynda, one of the co-hosts of the Laravel News and the North Meets South podcasts, explains how to easily uptime your models with data coming from requests.

Instead of littering your controller method with multiple request()->has(‘field’) checks, you can employ the request object’s intersect method. The intersect method will return a new array containing only the keys that are present in both the specified list and the request itself.

Using intersect allows you to easily handle a PATCH request – one where you partially update a resource’s data, rather than all of it as with a PUT – in a much more concise manner.

https://dyrynda.com.au/blog/partial-model-updates-in-laravel

Make git work better with GitHub

A few months ago I installed a command line utility called hub. I’m really fond of it. It’s aim is to make it easier to interact with GitHub from the commandline. It’s a wrapper around the standard git command. Once it’s installed you can do stuff like this (take from the manual page)

# clone your own project
$ git clone dotfiles
→ git clone git://github.com/YOUR_USER/dotfiles.git

# clone another project
$ git clone github/hub
→ git clone git://github.com/github/hub.git

# open the current project's issues page
$ git browse -- issues
→ open https://github.com/github/hub/issues
# Example workflow for contributing to a project:
$ git clone github/hub
$ cd hub
# create a topic branch
$ git checkout -b feature
  ( making changes ... )
$ git commit -m "done with feature"

# It's time to fork the repo!
$ git fork
→ (forking repo on GitHub...)
→ git remote add YOUR_USER git://github.com/YOUR_USER/hub.git

# push the changes to your new remote
$ git push YOUR_USER feature
# open a pull request for the topic branch you've just pushed
$ git pull-request

Want to use all this cool stuff too? Head over to the installation instructions on GitHub.

Comparing Vue with other frameworks

Recently I stumbled upon a page in the VueJs docs where Vue is compared against all other similar frameworks. I’m impressed with the fact that they reached out to authors of the other frameworks to get well balanced comparison.

This is definitely the most difficult page in the guide to write, but we do feel it’s important. Odds are, you’ve had problems you tried to solve and you’ve used another library to solve them. You’re here because you want to know if Vue can solve your specific problems better. That’s what we hope to answer for you.

We also try very hard to avoid bias. As the core team, we obviously like Vue a lot. There are some problems we think it solves better than anything else out there. If we didn’t believe that, we wouldn’t be working on it. We do want to be fair and accurate though. Where other libraries offer significant advantages, such as React’s vast ecosystem of alternative renderers or Knockout’s browser support back to IE6, we try to list these as well.

https://vuejs.org/v2/guide/comparison.html

Stack Overflow’s Developer Survey results

Every year Stack Overflow runs as survey where they asks their users about their favourite tools, languages, etc… A little while ago they published the results of the 2017 edition.

We learn something new every time we run our survey. This year is no exception:

– A common misconception about developers is that they’ve all been programming since childhood. In fact, we see a wide range of experience levels. Among professional developers, 11.3% got their first coding jobs within a year of first learning how to program. A further 36.9% learned to program between one and four years before beginning their careers as developers.
– Only 13.1% of developers are actively looking for a job. But 75.2% of developers are interested in hearing about new job opportunities.
– When we asked respondents what they valued most when considering a new job, 53.3% said remote options were a top priority. A majority of developers, 63.9%, reported working remotely at least one day a month, and 11.1% say they’re full-time remote or almost all the time.
– A majority of developers said they were underpaid. Developers who work in government and non-profits feel the most underpaid, while those who work in finance feel the most overpaid.

https://stackoverflow.com/insights/survey/2017/

Sharing Data in a Laravel/Vue Application

There are multiple good ways to pass data from Laravel to Vue. In a new blogpost Jesse Schutt covers all the options.

It has been helpful to think of my application as “layers” or separate sections of code each with varying responsibilities. I like to think of Laravel as the intermediary between the persistent data in the database, and the Vue components comprising the front-end of the app.

Though the boundaries between Laravel and Vue may appear unclear at the outset, the only way one can know about the other’s data is if it is explicitly passed. Blade templates implicitly know a lot about the application, but Vue operates on a different layer, so it only knows what we tell it. Fortunately, there are a number of ways to provide Vue with the data it needs.

https://zaengle.com/blog/layers-of-a-laravel-vue-application

A Laravel package to quickly dump and load the database

Last week our team released a new package called laravel-db-snapshots. It provides a few artisan commands to quickly dump and load a database. We’ve built this for is to help us develop features in an app that require the database to be in a specific state. With this package we can take a dump of the db, try out the feature that modifies the db. When there are bugs, we can fix them, load up the dump and try again.

Here’s how the package can be used:

# Create a dump
php artisan snapshot:create my-first-dump

# Make some changes to your db
# ...

# Create another dump
php artisan snapshot:create my-second-dump

# Load up the first dump
php artisan snapshot:load my-first-dump

# List all snapshots
php artisan snapshot:list

Currently the package has support for MySQL, PostgreSQL and Sqlite databases. To learn more about it head over to the readme on GitHub. If you like it, be sure to take a look at the other Laravel packages our team has previously built.