Sevalla is the all-in-one PaaS for your web projects. Host and deploy your applications, databases, object storage, and static sites. Enjoy advanced deployment pipelines, a complete database studio, instant preview apps, and one-click templates. The pricing is simple: no hidden fees, no seat-based pricing, and you pay only for what you use. Get real human support from developers.

Get started now with a $50 credit at Sevalla.com.

Easily work with the Twitter Streaming API in PHP

Original – by Freek Van der Herten – 3 minute read

Twitter provides a streaming API with which you can do interesting things such as listen for tweets that contain specific strings or actions a user might take (e.g. liking a tweet, following someone,...). In this post you'll learn an easy way to work with that API. Phirehose When researching on how…

Read more

How to contribute to an open-source GitHub project using your own fork

Link –

Serial blogger Matt Stauffer wrote a good tutorial on how use forked repos.

I just recently joined a new open source project, and there were a few folks on the team who weren't familiar with how to contribute to an open source project by forking your own copy, so I wrote this up for the docs of that project. I figured I'd also share it here.

If you join a new open source project, it's very likely that you won't get direct access to push commits or branches up to the repository itself. So, instead, you'll fork the repo, make the changes on your version of the repo, and then "pull request" your changes back to the original.

Here are the steps to take.

https://mattstauffer.co/blog/how-to-contribute-to-an-open-source-github-project-using-your-own-fork

Read more

Stay up to date with all things Laravel, PHP, and JavaScript.

You can follow me on these platforms:

On all these platforms, regularly share programming tips, and what I myself have learned in ongoing projects.

Every month I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.

A Laravel package to rebuild the database

Original – by Freek Van der Herten – 2 minute read

Out of the box Laravel comes with a few commands to migrate the database. One of them is migrate:refresh. That one will first run the down-steps for all your migrations and then run all the up steps. After that process your database should have the same structure as specified in your migrations. But…

Read more

Framework code complexity comparison

Link –

On his new blog on Medium, Taylor Otwell, creator of Laravel, published some statistics on the code complexity of various popular PHP frameworks. Draw your own conclusion.

Last week as I was refactoring and cleaning Laravel for the 5.4 release, Graham Campbell showed me some code complexity statistics for the framework. I decided to compare this against some other PHP frameworks to see how Laravel stacks up.

https://medium.com/@taylorotwell/measuring-code-complexity-64356da605f9

Recently Taylor sat down with the folks at Larachat. Watch the recording to learn some other nice interesting tidbits about Laravel and it's ecosystem.

Read more

Making overloaded functions readable

Link –

Sometimes you might allow a function to accept multiple data types. I don't know for certain if it's the correct term but for the remainder of this post I'm going to call such a function overloaded. In this post I'd like to show you a little trick to make overloaded functions more readable.

Let's first take a look at a function in Laravel that accepts multiple data types. To store something in a session you can pass a key and value to the session helper:

session($key, $value);

But you can also give it an array:

session(['key' => 'value']);

Now behind the scenes Laravel is calling a put function. It could have been implemented like this:

public function put($key, $value = null)
{
    if (is_array($key)) {
       foreach ($key as $arrayKey => $arrayValue) {
           $this->set($arrayKey, $arrayValue);
       }
    }
    else {
       $this->set($key, $value);
    }
}

In the function above there's a path for doing the work if an array was passed and another path for when (hopefully) a string was passed.

The actual implementation is a bit different (and much better):

public function put($key, $value = null)
{
    if (! is_array($key)) {
        $key = [$key => $value];
    }

    foreach ($key as $arrayKey => $arrayValue) {
        $this->set($arrayKey, $arrayValue);
    }
}

The cool thing to note is that what the function first converts the passed arguments to a certain format (in this case an array) and then perform the work on the format. The actual work, the call to $this->set is only coded up once. When reading the source code of Laravel you'll often come across this pattern.

Let's take a look at another real life example to make the benefit of this pattern more clear. This next snippet is taken from a recent PR to the laravel-permission package. It aims to a add a query scope to a User model to perform the query only on users that have the given role(s). Roles can be passed through as an array, a string or an instance of Role.

/**
 * Scope the user query to certain roles only.
 *
 * @param string|array|Role|\Illuminate\Support\Collection $roles
 *
 * @return bool
 */
public function scopeRole($query, $roles)
{
    if (is_string($roles)) {
        return $query->whereHas('roles', function ($query) use ($roles) {
            $query->where('name', $roles);
        });
    }

    if ($roles instanceof Role) {
        return $query->whereHas('roles', function ($query) use ($roles) {
            $query->where('id', $roles->id);
        });
    }

    if (is_array($roles)) {
        return $query->whereHas('roles', function ($query) use ($roles) {
            $query->where(function ($query) use ($roles) {
                foreach ($roles as $role) {
                    if (is_string($role)) {
                        $query->orWhere('name', $role);
                    }

                    if ($role instanceof Role) {
                        $query->orWhere('id', $role->id);
                    }
                }
            });
        });
    }

    return $query;
}

The query is being build up in a few different ways depending on the type of the argument being passed through. The readability of this code can vastly be improved by:

  • first converting all arguments to a single format to work with
  • performing the work on that format
public function scopeRole($query, $roles)
{
    if ($roles instanceof Collection) {
        $roles = $roles->toArray();
    }

    if (! is_array($roles)) {
        $roles = [$roles];
    }

    $roles = array_map(function ($role) {
        if ($role instanceof Role) {
            return $role;
        }

        return app(Role::class)->findByName($role);
    }, $roles);

    return $query->whereHas('roles', function ($query) use ($roles) {
        $query->where(function ($query) use ($roles) {
            foreach ($roles as $role) {
                $query->orWhere('id', $role->id);
            }
        });
    });
}

In the snippet above all input, no matter what type is being passed through, is first converted to an array with Role objects. U sing that array the query is only being build up once. I should mention that the author of the PR did provide a good set of tests so it was very easy to refactor the code.

Let's do one more example. This one's taken from our laravel-fractal package which aims to make working with Fractal more developer friendly.

To return a response with json data you can to this in a Laravel app.

$books = fractal($books, new BookTransformer())->toArray();

return response()->json($books);

In the last version of our package a respond() method was added. Here's the equivalent code using the respond method.

return fractal($books, new BookTransformer())->respond();

You can pass a response code as the first parameter and optionally some headers as the second

return fractal($books, new BookTransformer())->respond(403, [
    'a-header' => 'a value',
    'another-header' => 'another value',
]);

You can also set the status code and the headers using a callback:

use Illuminate\Http\JsonResponse;

return fractal($books, new BookTransformer())->respond(function(JsonResponse $response) {
    $response
        ->setStatusCode(403)
        ->header('a-header', 'a value')
        ->withHeaders([
            'another-header' => 'another value',
            'yet-another-header' => 'yet another value',
        ]);
});

This is original code for the function that was submitted through a PR (slightly redacted):

public function respond($callbackOrStatusCode = 200, $callbackOrHeaders = [])
{
    $response = new JsonResponse();

    $response->setData($this->createData()->toArray());

    if (is_callable($callbackOrStatusCode)) {
        $callbackOrStatusCode($response);
    } else {
        $response->code($callbackOrStatusCode);

        if (is_callable($callbackOrHeaders)) {
            $callbackOrHeaders($response);
        } else {
            $response->withHeaders($callbackOrHeaders);
        }
    }

    return $response;
}

Sure, that code does the job. Unfortunately the real work (in this case: modifying $response) is done all over the place. Let's refactor! In the code below we're going to convert all input to callables first and then use them to modify $response.

public function respond($statusCode = 200, $headers = [])
{
    $response = new JsonResponse();

    $response->setData($this->createData()->toArray());

    if (is_int($statusCode)) {
        $statusCode = function (JsonResponse $response) use ($statusCode) {
            return $response->setStatusCode($statusCode);
        };
    }

    if (is_array($headers)) {
        $headers = function (JsonResponse $response) use ($headers) {
            return $response->withHeaders($headers);
        };
    }

    if (is_callable($statusCode)) {
        $statusCode($response);
    }

    if (is_callable($headers)) {
        $headers($response);
    }

    return $response;
}

Hopefully you can use this neat little trick to improve the readability of your code as well.

Read more

Pragmatic coding

Link –

Stefan Koopmanschap argues that, besides writing beautiful code and using kickass frameworks and libraries, we should be able to do some quick and dirty coding as well.

Can you write me a simple script that fetches some information from an RSS feed and displays the titles? Like, just write me that script in a couple of minutes. I don't care about tests, quality, etc. Just get me the information, quickly.

http://leftontheweb.com/blog/2017/01/04/pragmatic_coding/

Read more

How PHP Executes – from Source Code to Render

Link –

On the excellent PHP section of Sitepoint Thomas Punt has written a good high ievel overview of how PHP code is executed.

There’s a lot going on under the hood when we execute a piece of PHP code. Broadly speaking, the PHP interpreter goes through four stages when executing code:
  • Lexing
  • Parsing
  • Compilation
  • Interpretation

This article will skim through these stages and show how we can view the output from each stage to really see what is going on. Note that while some of the extensions used should already be a part of your PHP installation (such as tokenizer and OPcache), others will need to be manually installed and enabled (such as php-ast and VLD).

https://www.sitepoint.com/how-php-executes-from-source-code-to-render/

Read more

Quickly open a GitHub page from your terminal

Link –

At Spatie we use GitHub for both our client projects as our open source code. So in our day to day work we often have to open the browser to view issues of a repo or review pull requests.

Paul Irish, a well known developer and part of the Google Chrome team at Google, made a nice bash script to quickly open up a GitHub page from your terminal. If you're on a path inside a git repo and type "git open" that'll open up the corresponding page on GitHub.

The command also supports, amongst others, repos hosted on GitLab.com and Bitbucket.

https://github.com/paulirish/git-open

Read more

Using Varnish on a Laravel Forge provisioned server

Original – by Freek Van der Herten – 12 minute read

For a project we're working on at Spatie we're expecting high traffic. That's why we spent some time researching how to improve the request speed of a Laravel application and the amount of requests a single server can handle. There are many strategies and services you can use to speed up a site. In…

Read more

10 things I learned making the fastest site in the world

Link –

David Gilbertson made a lighting fast site and wrote a fantastic article about it.

Writing a fast website is like raising a puppy, it requires constancy and consistency (both over time and from everyone involved). You can do a great job keeping everything lean and mean, but if you get sloppy and use an 11 KB library to format a date and let the puppy shit in the bed just one time, you’ve undone a lot of hard work and have some cleaning up to do.

https://hackernoon.com/10-things-i-learned-making-the-fastest-site-in-the-world-18a0e1cdf4a7

Read more

A collection of PHPStorm tips

Link –

Nikush Patel created an awesome little site where he shares PHPStorm tips. Every tip is demonstrated by an animated gif.

I'm a big fan of PhpStorm and an equally big fan of keyboard shortcuts and optimised workflows, so I wanted to share all the best tips and tricks I know to help everyone else make the most of PhpStorm as well!

I produce useful tips in bite-sized gif recordings so they are easier to consume than reading the docs.

http://phpstorm.tips/

Read more

Setting up Xdebug with Laravel Valet

Original – by Freek Van der Herten – 4 minute read

On most of my day to day work I use Laravel Valet to develop locally. When hitting a bug often I just put a dd() statement in the code to quickly inspect what's going on. But when encountering a complex bug this becomes tedious. Wouldn't it be nice if we could add a breakpoint to our code and be…

Read more

PHP 5: Active Support Ends. Now what?

Link –

Starting from tomorrow PHP 5.6. will not be actively supported anymore. Sebastian Bergmann, author of PHPUnit explains how PHP's release process works, and what the ending of active support means for you. Spoiler: you should upgrade asap.

It is high time to think about upgrading your PHP stack to PHP 7, ideally to PHP 7.1. This should be a short-term goal for you.

Upgrading the version of PHP you use must not be a rare event you are afraid of. You must not think of upgrading your PHP stack as a "special project". You need to make upgrading the PHP version you use part of your normal operational procedure and align the upgrade cycle of your PHP stack with the release cycle of the PHP project. This should be a long-term goal for you.

https://thephp.cc/news/2016/12/php-5-active-support-ends-now-what

Read more

Looking back on the year

Link –

Laravel News published a nice overview of what happened in the Laravel ecosystem in 2016.

As 2016 is coming to a close it’s a great time to look back on the year and see just how much progress has been made. Laravel had a busy year with 5.3 being released, Laracon, updates to all the components, and now gearing up for the Laravel 5.4 release.

To look back on the year I’ve put together a list of some of the hits of 2016 and arranged them by month so you can get a quick overview of all the highlights.

https://laravel-news.com/80-laravel-tutorials-packages-and-resources

The Laravel ecosystem sure is moving fast. For me the best new software that emerged from it was Laravel Valet. I use it for most projects now and can't imagine working on a Vagrant box anymore for my normal day to day work. Hopefully Valet will gain more recognition in the greater PHP community in 2017.

I'm also happy to report that the Laravel / PHP packages my company releases have grown in popularity in 2016.

Read more

A thousand best replies on the Laracasts forum

Link –

On the Laravel Daily blog Povilas Korop published an interview with Bobby Bouwmann. In the past two years Bobby earned almost a thousand best reply awards, an amazing accomplishment.

In recent years, Laracasts has become a no.1 resource for learning Laravel. Also, there’s a really active discussion forum on the website, so we decided to chat with one of the most active members there. Bobby Bouwmann has almost 1000 “Best Reply” awards on the forum, which is a huge number. So what is it like to be so active on Laracasts? Let’s find out.

http://laraveldaily.com/bobby-bouwmann-lessons-1000-best-replies-laracasts/

Read more

Inside PHP 7's performance improvements

Link –

On the Blackfire.io blog Julien Pauli peeks behind the curtains of PHP. In the five part series he explains how you should write your code to make the best use of the internal optimizations present in PHP 7.

This blog series will show you what changed inside the Zend engine between PHP 5 and PHP 7 and will detail how you, as a developer, may effectively use the new internal optimizations. We are taking PHP 5.6 as a comparison basis. Often, it is just a matter of how things are written and presented to the engine. Performance must be taken care of when critical code is written. By changing some little things, you can make the engine perform much faster, often without losing other aspects such as readability or debugging control.

https://blog.blackfire.io/php-7-performance-improvements-packed-arrays.html

Read more

Dealing With Templates in Vue.js 2.0

Link –

Sebastian De Deyne, my colleague at Spatie, wrote a very nice overview of all different methods in Vue to define a template.

This article isn't about Vue's template syntax, but about where and how to define your templates. I wrote this because at the time of writing there aren't really resources that consolidate all the different manners to manage your templates.

I've divided the different ways to define templates in three different categories, each with their own drawbacks:

  • Writing templates that compile at runtime (lesser performance)
  • Using single file .vue components (requires a build step)
  • Manually writing render functions (pure JavaScript, no html-like template syntax)

https://sebastiandedeyne.com/posts/2016/dealing-with-templates-in-vue-20

Read more

Optimizing PHP performance by using fully-qualified function calls

Link –

A fully qualified function name is a little bit faster than a non-qualified one. Toon Verwerft explains it all in his lastest blogpost.

Today, a little conversation on Twitter escalated rather quickly. Apparently PHP runs function calls differently depending on namespaced or non namespaced context. When calling functions in a namespaced context, additional actions are triggered in PHP which result in slower execution. In this article, I'll explain what happens and how you can speed up your application.

http://veewee.github.io/blog/optimizing-php-performance-by-fq-function-calls/

Read more

Creating an audio waveform from your microphone input

Link –

Sam Bellen, an engineer at madewithlove, explains how to draw an audio form in real time using the sound from your computer's microphone.

I've recently started creating an online audio editor. One of the features I wanted to implement was to create a waveform for each track in the editor. This gives a nice overview of the content of each track.

While recording a new track, it would be cool to visually see the the waveform you're recording so I decided to generate a waveform in realtime while recording a new audio track.

Below I will go through the basics of how you can create such a waveform from your audio input device.

https://blog.sambego.be/creating-an-audio-waveform-from-your-microphone-input/

Read more

Overriding Laravel's helper functions

Link –

Miklós Galicz posted a short article on how he managed to override Laravel's str_slug helper function.

Long story short, until this is resolved one way or another... A really obscure but powerful tool can be a temporary solution for this. It's called Helper Overloading. Laravel's helpers are created in a way that checks if the method already exists. ... This is really great, the only thing remaining is to actually add our own method before Laravel creates it own version.

https://blackfyre.ninja/blog/fixing-slug-generation-problems

Read more