How to organize a meetup

On his blog Jef Claes, organiser of DDDBE, shares some good tips on how to organize a meetup.

I’ve organized a few DDDBE meetups in the past, and always succeed in forgetting something. Either someone points it out well in advance, or I end up stressing last minute. This post partly serves as a checklist for myself, but it would be a welcome side effect to also see it encourage others to help out organizing future meetups. Organizing a meetup is not rocket science, having a list of what to take care of is a good start.

http://www.jefclaes.be/2017/02/how-to-organize-meetup.html

Glossary of Modern JavaScript Concepts

Don’t know what the difference between stateful and stateless is, or what higher order functions are? On the auth0.com site Sebastián Peyrott explains these terms and other modern JavaScript concepts.

Modern JavaScript has experienced massive proliferation over recent years and shows no signs of slowing. Numerous concepts appearing in JS blogs and documentation are still unfamiliar to many front-end developers. In this post series, we’ll learn intermediate and advanced concepts in the current front-end programming landscape and explore how they apply to modern JavaScript.

https://auth0.com/blog/glossary-of-modern-javascript-concepts/

A Laravel package to impersonate users

A great feature of Laravel Spark is it’s ability to impersonate other users. As an admin you can view all screens as if you are logged in as another user. This allows you to easily spot a problem that your user might be reporting. Laravel-impersonate is a package, made by MarceauKa and Thibault Chazottes that can add this behaviour to any Laravel app.

Here are some code examples taken from the readme.

Auth::user()->impersonate($otherUser); // You're now logged as the $otherUser.

Auth::user()->leaveImpersonation(); // You're now logged as your original user.

$manager = app('impersonate');

// Find an user by its ID
$manager->findUserById($id);

// TRUE if your are impersonating an user.
$manager->isImpersonating();

// Impersonate an user. Pass the original user and the user you want to impersonate
$manager->take($from, $to);

// Leave current impersonation
$manager->leave();

// Get the impersonator ID
$manager->getImpersonatorId();

It even includes some handy blade directives:

@canImpersonate
    <a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a>
@endCanImpersonate

@impersonating
    <a href="{{ route('impersonate.leave') }}">Leave impersonation</a>
@endImpersonating

Want to know more, take a look at the package on GitHub.

Laravel’s tap helper function explained

A little known helper function, called tap was added to Laravel 5.3. In this short post I’ll explain how this function can be used.

Let’s first take a look at the tap function itself. It’s actually a very short one.

function tap($value, $callback)
{
   $callback($value);

   return $value;
}

So you give it a $value and a $callback. The $callback will execute with the $value as the argument. And finally the $value will be returned.

Nice, but how is it used in the wild? Let’s take a look at the pull function in Illuminate\Cache\Repository. This function will get the value out of the cache for the specified key and forget it.

This is how it could have been implemented:

public function pull($key, $default = null)
{
   $value = $this->get($key, $default);

   $this->forget($key) // returns a boolean;

   return $value;
}

In the example above $this->forget() returns a boolean. So to have our function return the original value, we need to store it in the temporary variable $value first.

This is the actual implementation in Laravel.

public function pull($key, $default = null)
{
   return tap($this->get($key, $default), function ($value) use ($key) {
      $this->forget($key);
   });
}

In the snippet above there’s no need anymore for a temporary variable. Win! Now, you might argue that it’s less readable. If the arrow functions rfc gets accepted, it can be rewritten as a one liner.

public function pull($key, $default = null)
{
   return tap($this->get($key, $default), fn($value) => $this->forget($key));
}

Want to see some more usages of tap? Take a look at the Laravel source code. There’s also a tap method on the Collection class. Read this post on Laravel news to see a few examples.

Environment variables, config caching, and Laravel

In a short blogpost Michael Dyrynda gives some good advice on why you should cache your routes and config values.

As part of the recommended production deploy process it is important to run the caching commands that Laravel affords us via Artisan. This means running config:cache and route:cache, which will compile the config and route files down into a single file each.

In doing so, Laravel aims to speed up parsing of these files by only needing to read a single, rather than multiple files.

https://dyrynda.com.au/blog/environment-variables-config-caching-and-laravel

Getting started with Varnish Cache

If you want to learn Varnish Thijs Feryn wrote a book for you. It’s free to download until 7th March 2017.

Getting Strated with Varnish Cache is a technical book about the Varnish caching technology. Varnish is a so-called reverse caching proxy that acts as an intermediary between the browser and the webserver. Varnish stores HTTP responses and serves them to the browser, without accessing the backend for every request. This causes a massive speed increase.

https://blog.feryn.eu/my-varnish-book-is-now-available/

Understanding Laravel’s macroable trait

Nicola Malizia wrote a short blog post on how Laravel’s handy Macroable trait can be used and how it works under the hood.

If you check the Laravel codebase I’m sure that you can observe that Laravel makes use of traits.There is one trait in the source code that pulls my attention. I’m talking about the Macroable trait.

The purpose of this trait is to extend (not in an OOP sense) a class at run-time. This way, you can add behavior without editing the original class source code.

https://unnikked.ga/understanding-the-laravel-macroable-trait-dab051f09172

Packages that make developing Laravel apps easier

In this post I’d like to share some of the packages that make developing a Laravel app easier.

laravel-debugbar

This package really needs no introduction as it is one of the most popular packages around. It’s made by Barry Vd. Heuvel and it’s a real powerhouse. Once the package is installed it displays a debugbar in your browser that shows a lot of useful info such as the executed queries, which views are used, which controller built up the page, and much much more.

https://github.com/barryvdh/laravel-debugbar

laravel-ide-helper

This package, also made by Barry, can generate some files that help an IDE provide improved autocompletion. Using this package PHPStorm can autocomplete methods on facades, classes resolved out of the container and model properties.

https://github.com/barryvdh/laravel-ide-helper

laravel-tail

Those who are already using Laravel for quite some time know that Laravel 4 provided an artisan command to tail the Laravel default log. Unfortunately in Laravel 5 that command was axed. This package brings it back.

With the package installed you can just run php artisan tail to tail the log.

https://github.com/spatie/laravel-tail

laravel-mailable-test

Laravel 5.3 introduced mailables. A mailable is a class that takes care of everything regarding sending a mail.

One of the things that is not so easy to in a vanilla Laravel app is testing such a mail. In order to for example let your app send an order confirmation mail you have to go through the entire checkout process. The laravel-mailable-test package can make the mailable testing process a lot easier. It provides an artisan command that can send a mailable to a specific mail address.

The package will provide a value for any typehinted argument of the constructor of the mailable. If an argument is a int, string or bool the package will generated a value using Faker. Any argument that typehints an Eloquent model will receive the first record of that model.

If you want to learn more, read this introductory blog post about it.

https://github.com/spatie/laravel-mailable-test

laravel-mail-preview

Made by Mohamed Said, this package can help you test a flow where mail is involved. Instead of sending the actual mail that package will save the mail to the filesystem. In the browser it will display a little notice that a mail was sent. Clicking on the link in that notice will display the saved mail right in your browser.

Here’s a short movie clip that shows how it can be used to test a password reset.

https://github.com/themsaid/laravel-mail-preview

laravel-migrate-fresh

In my projects I have never run a down migration. So I don’t bother with coding up the down steps. And without those down steps running Laravel’s migrate:refresh will result in errors. If you think skipping writing down steps is lazy, read this comment Adam Wathan made on Reddit.

The laravel-migrate-fresh package provides an artisan command that can knock out all your tables without using down steps of a migration.

https://github.com/spatie/laravel-migrate-fresh


Do you know some other indispensable package that makes developing a Laravel app easier? Let me know in the comments below.

Polyfills: everything you ever wanted to know, or maybe a bit less

David Gilbertson tells you all about polyfills.

Faced with the reality that you can’t write modern code and expect it to work for all users, you have exactly two choices:

1. Only use language features available in all the browsers you support
2. Write modern code, then do something to make it work in older browsers

If you have decided on option one then I respectfully suggest that you are bonkers, and insist that you state your case in the comments.
I believe that developers who are able to explore all the new stuff and use it in their day-to-day jobs stay happy, and being happy is important.

https://hackernoon.com/polyfills-everything-you-ever-wanted-to-know-or-maybe-a-bit-less-7c8de164e423

Moving tech forward with Gomix, Express, and Google Spreadsheets

Matt Stauffer wrote down his experiences with creating a simple app on Gomix, a platform to easily create node powered sites right in your browser.

Gomix is a platform that makes it absurdly easy to spin up a new app (static HTML or Node) and see it online instantly. You can also invite your friends to collaborate, and the moment you make a change in the editor, your site updates. So, at this point I’m using Gomix and Node, and Express is an easy pick.

I strongly considered using Firebase for data storage, but the Gomix team linked me to this Gomix site using Google Spreadsheets as the backing data source and I really wanted to try it out.

So we’ve now settled: I’ll take my old HTML and JavaScript, but instead of the JavaScript loading its data from JSON files, I’ll run an Express app on Gomix pulling the data from Google Spreadsheets and output its data in a JSON format. No big deal.

https://mattstauffer.co/blog/moving-tech-forward-with-gomix-express-and-google-spreadsheets

A package to remember a visitor’s original referer

If you want to know how a visitor got on your site you can check the referer request header. Yeah, it’s misspelled. That header contains the url of the previously visited page. Unfortunately browsers will fill that header regardless of the previous url was an internal or external one. So after the first click on an internal link you won’t know anymore on which site a visitor was on previously.

Our new laravel-referer package aims to fix that problem. Once the package is installed it will remember the original referer in session. So even after a users clicks around on your site, you are still able to detect which site he or she visited previously.

Because users are also often tracked using UTM Codes the package will also remember the utm_source query parameter.

The easiest way to retrieve the referer is by just resolving it out of the container:

use App\Spatie\Referer\Referer;

$referer = app(Referer::class)->get(); // 'google.com'

Or you could opt to use Laravel’s 5.4 fancy new automatic facades:

use Facades\Spatie\Referer\Referer;

$referer = Referer::get(); // 'google.com'

To know more take a look at the readme of the package on GitHub.

https://github.com/spatie/laravel-referer

Add syntactic sugar by preprocessing PHP

In an awesome article at Sitepoint Christopher Pitt explains how he used the yay macro library to build up plugin framework to add new language features to PHP.

Chris made plugins that allows this syntax in PHP.

// short closure syntax
$items = ["one", "two", "three"];
$ignore = "two";

array_filter($items, ($item) => {
    return $item !== $ignore;
});
//class accessors

class Sprocket
{
    private $type {
        get {
            return $this->type;
        }

        set {
            $this->type = $value;
        }

        unset {
            $this->type = "type has been unset";
        }
    }
}

As with all things, this can be abused. Macros are no exception. This code is definitely not production-ready, though it is conceptually cool.

Please don’t be that person who comments about how bad you think the use of this code would be. I’m not actually recommending you use this code, in this form.

Having said that, perhaps you think it’s a cool idea. Can you think of other language features you’d like PHP to get? Maybe you can use the class accessors repository as an example to get you started. Maybe you want to use the plugin repository to automate things, to the point where you can see if your idea has any teeth.

https://www.sitepoint.com/how-to-make-modern-php-more-modern-with-preprocessing/

Check out some more examples on preprocess.io

Very cool stuff.

A package to easily manipulate images in PHP

Today we released a new package called image that makes manipulation images in PHP extremely easy. In this post I’d like to explain why we built it and how it can be used.

Manipulating images in PHP

To manipulate images in PHP there are already a lot of options. You can go hardcore and use the Gd or Imagick functions directly. By using them you get a lot of control, but most of these functions aren’t very developer friendly. If you need something easier to work with try out the Intervention Image library by Oliver Vogel. It provides a nice abstraction and will make working with images a lot easier.

Another option is a package by Jonathan Reinink called Glide. This one is a bit special. Glide can generate images on the fly using url parameters. With Glide installed in your project a cropped version of the image in this bit of html will be automatically generated.

<img src="image.jpg?w=300&h=400&fit=crop" />

Its API is really nice to work with. Under the hood Glide leverages the aforementioned Intervention Image but it hides some of the complex operations behind easy to use parameters. Unfortunately Glide only exposes its API via http, there’s no way to easily programmatorically work with it.

Our image package

Enter spatie/image. Our new package wraps up Glide so all its methods can be used using PHP code.

Basic manipulation

In the remainder of this article we are going to manipulate this beautiful photograph taken in New York City.

Let’s start of with a simple manipulation.

Image::load('new-york.jpg')
    ->sepia()
    ->blur(50)
    ->save();

Here’s the result:

Let’s perform crop out that Starbucks storefront.

Image::load('new-york.jpg')
    ->manualCrop(600, 400, 20, 620)
    ->save();

Check out the documentation to learn which operations the package support.

Converting to other formats

Imagine you want to convert a jpg to a png. Here’s how to do that.

Image::load('new-york.jpg')->save('converted.png');

It couldn’t be more simpler, the package will just use the extension of the output file to determine the output format.

Applying changes

By default every manipulation will only be applied once to your image. When calling a manipulation method multiple times only the last call will be applied when the image is saved.

Take a look at this code.

Image::load('new-york.jpg')
    ->brightness(-40)
    ->brightness(-20)
    ->save();

The second call to brightness will override the value set by the first call to brightness. So the resulting image will only have its brightness reduced by 20%.

The apply method will apply all previous manipulations to the image before continuing with the next manipulations.

Image::load('new-york.jpg')
    ->brightness(-40)
    ->apply()
    ->brightness(-20)
    ->save();

That code will lower the brightness by 40%, then lower it again by 20%. The result:

Preparing manipulations

In the previous examples all manipulations like brightness and blur were called directly on the Image instance. You could also opt to build up a Manipulations instance.

$manipulations = (new Manipulations())
    ->blur(20)
    ->brightness(-20);

and then you can use that to manipulate a collection of images.

//using Laravel's collect function

collect($images)->each(function(Image $image) use ($manipulations) {
    $image
       ->manipulate($manipulations)
       ->save();
}

The manipulate function can also accept a closure.

$image->manipulate(function(Manipulations $manipulations) {
    $manipulations
       ->blur(20)
       ->brightness(-20);
});

In closing

You’ll find more examples of how you can use spatie/image in the documentation. Right now we’re using Glide behind the scenes to perform the manipulations, but we’ve built up our package in such a way that, in theory, we could swap Glide out for something else, without making any breaking changes.

If you use Laravel and need a good solution to handle images and other files in your app, then check out our laravel-medialibrary package. We’re releasing a new major version soon where all image manipulations are powered by spatie/image.

Also take a look at the PHP and Laravel packages we’ve previously built. Maybe we’ve made something that you can use in your next project.

A link blog to stay in touch with the bigger PHP community

Probably because I’m a heavy user of Laravel I read a lot of Laravel focused blogs and follow a lot people on Twitter who also are heavy users of the framework. But more than a Laravel developer, I consider myself a PHP developer first. One of the ways I try to stay in touch with what is happening in the larger PHP community is following this excellent link blog maintained by Chris Cornutt.

http://www.phpdeveloper.org/

Configuration-driven PHP security advice considered harmful

Scott Arciszewski debunks the commonly given advice on securing your PHP installation by setting some php.ini values.

There have been countless examples posted in various places (Reddit, Hacker News, Twitter, Facebook, Slashdot, and even LinkedIn group discussions), and while a handful occasionally contain one or two tips that might be beneficial towards securing your PHP applications, almost all of the advice they contain is either wrong, a huge waste of time, downright silly, or all of above.

As part of a team that specializes in application security (in particular: securing PHP applications), I feel it’s high time someone cleared the air about this advice.

https://paragonie.com/blog/2017/01/configuration-driven-php-security-advice-considered-harmful

Why a software patch is called a patch

Bram Van Damme explains the origin of the word “patch” in context of software.

A common misconception is that a software bug is called a bug because of an actual bug – a moth – that got stuck in Harvard University’s Mark II calculator in 1947, and Grace Hopper finding it + taping it inside a logbook.

What seems to be legit however is the history of the term software patch.

https://www.bram.us/2017/01/24/why-a-software-patch-is-called-a-patch/

Methods Are Affordances, Not Abilities

In a new post on his blog Adam Wathan explains his thinking on the meaning of having a method on an object.

The fundamental misunderstanding here is thinking that methods are things an object can do.

If you believe that the methods on an object represent the abilities of that object, then of course an Announcement having a broadcast() method sounds silly.

But what if methods weren’t the things an object could do? What if they were the things you could do with that object?

If methods were the actions an object afforded us, then it would make perfect sense to be able to broadcast() an Announcement, wouldn’t it?

https://adamwathan.me/2017/01/24/methods-are-affordances-not-abilities/

An artisan command to easily test mailables

Most of the Laravel apps we create at Spatie will send mails. This can be a password reset mail, a welcome mail after registration, an order confirmation mail, … One of the things we do is styling such mails so it has the same look and feel as the site it was sent from. When testing such mails our designers had to request a password reset or go through the entire checkout flow just to receive such an order confirmation mail. To make that testing process a lot easier we’ve created a package called laravel-mailable-test. This package provides an artisan command that can send a mailable to an mail-address.

To send any mailable issue this artisan command:

php artisan mail:send-test "App\Mail\MyMailable" [email protected]

This will send the given mailable to the given email address. The to-, cc- and bcc-addresses that may be set in the given mailable will be cleared. The mail will only be sent to the email address given in the artisan command.

The package will provide a value for any typehinted argument of the constructor of the mailable. If an argument is a int, string or bool the package will generated a value using Faker. Any argument that typehints an Eloquent model will receive the first record of that model.

Image the constructor of your mailable looks like this:

public function __construct(string $title, Order $order) 
{
   ...
}

That constructor will receive a string generated by the sentence method of Faker and the first Order in your database.

The values that are passed to the constructor of the mailable can be customized using the values option of the command.

php artisan mail:send-test "App\Mail\MyMailable" [email protected] --values="title:My title,order:5"

Using this command My title will be passed to $title and an Order with id 5 will be passed to $order.

To learn more about the package head over to the readme on GitHub. Be sure take also take a look at this list of Laravel packages our team has previously made.

Switching PHP versions with Laravel Valet

Michael Dyrynda, one of the two new hosts of the Laravel Podcast, share a nice tip on how to quickly switch PHP versions when using Laravel Valet.

At the time of writing, Laravel Valet ships with PHP 7.1 but if you’re like me, you have some legacy projects around the place that haven’t quite lifted their dependencies to PHP 7 just yet.

A lot of folks might have previously used a VirtualBox Virtual Machine, or more recently considered Docker but a lot of the time and especially when dealing with simpler situations, Valet may be all that you need.

https://dyrynda.com.au/blog/switching-php-versions-with-laravel-valet