Commands, events, global functions and testing

Tony Messias on the madewithlove-blog:

The other day I was listening to the FullStackRadio episode 34 which is about dealing with dependencies in Active Record models. This is a very interesting topic and they suggest a few solutions for it. I liked the suggestions and I tried to implement it differently (first try and second try).

After that, I decided to talk to my colleagues about the design implementations. And they asked “why not implementing it as a command?”. At first sight I was a bit reluctant, because I’m starting to think applications are getting more complex then it really needs. Then I decided to implement it and the end result was the best one to us. Let’s discuss it a bit.

http://blog.madewithlove.be/post/commands-events-global-functions-and-testing/

Read more

Get notified when a queued job fails

Laravel provides excellent support for queued jobs. It's very easy to put something on a queue and out of the box a lot of queue backends such as Beanstalkd, SQS and Redis are supported. Most of the time queued jobs will perform their job without any problem. But have you considered that a queued job can fail too?

Laravel can create a failed jobs table and write a record when a queued jobs fails. There is even a command to retry a failed job:

php artisan queue:retry 5

That's nice! But how do you know if there is a job that failed? Sure you could check the failed jobs table from time to time, but I promise you after a while you won't do that anymore. If you have many applications, checking all those failed job tables will get downright tedious.

To get notified when a queued job fails our intern Jolita created a package called failed job monitor. It hooks into the JobFailed-event Laravel 5.2 fires when a queued job fails. Once it is installed you will receive a mail whenever this event occurs. Integration with Slack comes built-in as well. Here's how a Slack notification looks like:

failed job

Read the full instructions on how to install and use it on GitHub.

Read more

Join 9,500+ smart developers

Get my monthly newsletter with what I learn from running Spatie, building Oh Dear, and maintaining 300+ open source packages. Practical takes on Laravel, PHP, and AI that you can actually use.

No spam. Unsubscribe anytime. You can also follow me on X.

A package to dump your database original

by Freek Van der Herten – 1 minute read

A few weeks ago I released a package called db-dumper. The package can dump the structure and contents of a database to a file. Here's how it can be used: Spatie\DbDumper\Databases\MySql::create() ->setDbName($databaseName) ->setUserName($userName) ->setPassword($password)…

Read more

Heroes of PHP

Following the conclusion of the 24 Days in December series on PHP, I originally posted my own 24 “Heroes of PHP”™ on Twitter.

I’m reproducing that list here, together with some additional explanation of why these individuals mean so much to me.

...

These are just some of my personal heroes, inspirations and role models, I’m sure that you have your own “Heroes of PHP”; but they all deserve thanks for the time and effort that they devote to improving our lives as PHP developers.

http://markbakeruk.net/2016/01/26/heroes-of-php-1/

Read more

Take a deep dive in Laravel's router

Over at Envato Tuts Matthew Machuga published a video explaining Laravel's router code. Going over Laravel's internal code (and other people's code in general) is always good method of learning new bits 'n' tricks.

In this lesson, we’ll explore the intricacies of Laravel Router. We’ll talk about the fundamentals of HTTP routing, before we go on to analyze some of the decisions and nuances in the design of Laravel Router. We’ll also talk about some of the awesome features that have been recently added to the router.
http://code.tutsplus.com/courses/how-its-made-laravel-router/lessons/how-its-made-laravel-router

Can't get enough Machuga? Then listen to the Full Stack Radio podcast, he's been a guest there several times. He's also one of the speakers of this year's Laracon US.

Read more

Monkey patching in PHP with Patchwork

Patchwork is a PHP library that allows you to change user defined functions at runtime. This can be incredibly handy when testing. I'm by no means a Ruby expert but I heard that in the Ruby world they do this kind of stuff all the time during testing.

Here's a simple example of what Patchwork can do:

function myCounter($array)
{
    return count($array);
}

myCounter([1, 2]); // returns '2';

//now let's change the function
Patchwork\redefine('myCounter', function($array)
{
    return count($array) ? 'a lot of items' : 'empty';
});

myCounter([1, 2]); // returns 'a lot of items";

Read the implementation docs to learn how this works behind the scenes.

Read more

Handling composers "lock file out of date" warning

Lorna Jane Mitchell explains on her blog which options you have when you see "lock file out of date" warning.

The `composer.lock` also includes a hash of the current `composer.json` when it updates, so you can always tell if you've added a requirement to the `composer.json` file and forgotten to install it.

In that case, you'll see an error message like:

Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. Run update to update them.

You now have three options: upgrade everything, figure it out, or do nothing.

http://www.lornajane.net/posts/2016/handling-composer-lock-file-out-of-date-warning

Read more

Messages in PHP

Matthias Noback continues his highly interesting series of posts with programming guidelines. Part four is about messages.

Besides having a type and a particular value, messages can also be categorized:
  • A command message is a request for change. One object wants to make the other object do something.
  • A query message is a request for information. One object wants to get something from the other object.
  • A document message is the response from the other object, based on the query that was sent to it.
https://www.ibuildings.nl/blog/2016/02/programming-guidelines-part-4-messages

Read more

Typed arrays in PHP

Tim Bezhashvyly recently wrote an article in which he explains an interesting approach to make sure all items in array are of a certain type. It leverages variadic functions which were introduced in PHP 5.6

Consider this piece of code (borrowed from Tim's post):

function foo (Product ...$products )
{
/* ... */
}

In PHP 7 you can even using the scalar types, such as string and int, to make sure all elements are of that type.

Read Tim's full article here: https://thephp.cc/news/2016/02/typed-arrays-in-php

Read more

Making the PHPBenelux Conference happen

Thys Feryn, one of the organisers of the PHPBenelux conference, wrote a lengthy article about what it takes to organize a big conference.

The PHPBenelux Conference edition 2016 took place last week in Antwerpen (Belgium). As an organizer, I’m really happy with the end result. I like to think that our attendees, speakers and sponsors also enjoyed it. It’s the 7th time we organize the PHPBenelux Conference and every year we try to introduce something new. Although the 7 years of experience and the well-organized crew have made it a lot easier to organize, it’s still a lot of work.

This post gives you a behind the scenes look at what it takes to organize the PHPBenelux Conference. It will reflect our passion, our strengths and our weaknesses.

https://blog.feryn.eu/making-the-phpbenelux-conference-happen/

Screen Shot 2016-02-10 at 18.38.21

Read more

Using Cron Jobs with Laravel and AWS Elastic Beanstalk

Philip Brown on his blog:

Almost every type of application will require scheduled jobs in one form or another. This could be automated emails, generated reports, or periodic notifications to your users.

Cron Jobs are a simple way to trigger these types of processes on a given schedule. But setting up Cron Jobs in a world of ephemeral servers is not so straight forward.

In today’s tutorial we’re going to be looking at setting up Cron jobs on AWS’ Elastic Beanstalk.

http://culttt.com/2016/02/08/setting-up-and-using-cron-jobs-with-laravel-and-aws-elastic-beanstalk/

Read more

Using emoji in PHP original

by Freek Van der Herten – 1 minute read

Using plain PHP it's kinda hard to display emoji characters. In PHP 5 those characters could be generated by using json_encode. echo json_decode('"\uD83D\uDE00"'); //displays ? I bet no one can type this code by heart. In PHP 7 it's a little bit easier. The hot new version of PHP…

Read more

Automatically test the quality of your code on commit

A few days ago Toon Verwerft gave an uncon talk at PHP Benelux Conference about a new code quality checking tool he has been developing. It's called GrumPHP. It can automatically perform various code quality checks when you try to commit some code.

Sick and tired of defending code quality over and over again? GrumPHP will do it for you! This composer plugin will register some git hooks in your package repository. When somebody commits changes, GrumPHP will run some tests on the committed code. If the tests fail, you won't be able to commit your changes. This handy tool will not only improve your codebase, it will also teach your co-workers to write better code following the best practices you've determined as a team.
https://github.com/phpro/grumphp

The slides of Toon's talk can be found on speakerdeck.

Read more

Monkey patch PHP classes with the BetterReflection Library

At the PHP Benelux conference James Titcumb did a presentation on the BetterReflection library he's working on. You can view the slides of his presentation on SlideShare.

The BetterReflection library has a few advantages over PHP's native reflection capabilities (copied from the docs):

  • you can reflect on classes that are not already loaded, without loading them
  • ability to reflect on classes directly from a string of PHP code
  • better Reflection analyses the DocBlocks (using phpdocumentor/type-resolver)
  • reflecting directly on closures
When this pull request will get merged the library even makes it possible to monkey patch classes. Let's take a look how you would do that.

Consider this class:

class MonkeyPatchMe
{
    function getMessage() : string
    {
        return 'hello everybody';
    }
}

The body of the getMessage-function can be replaced using this code:

$classInfo = ReflectionClass::createFromName('MonkeyPatchMe');

$methodInfo = $classInfo->getMethod('getMessage');

$methodInfo->setBody(function() {
   return 'bye everybody';
});

$monkeyPatchedClass = new MonkeyPatchMe();
$monkeyPatchedClass->getMessage() // returns 'bye everybody'


Behind the scenes this voodoo works by copying the original class to another file, doing a replacement of the function body there and loading up that class.

I'll be keeping my eye on how the BetterReflection library evolves. You can read all about it's current functionality in the docs on GitHub.

Read more

Getting rid of null

Matthias Noback published the second article in his programming guidelines series. This time he explains why using null in a function isn't a good idea. In my opinion it's great advice that most devs can immediately apply in their projects.

It's certainly a good idea to get rid of the uncertainty and vagueness that null brings to your code. Besides, most of the time when you encounter an actual null value in your program, you probably weren't expecting it. You just call a method on it, thinking that it is an object and PHP will rightfully let your program crash.

...

Every particular null situation requires a different solution, but at least I'll list several common solutions for you.

https://www.ibuildings.nl/blog/2016/01/programming-guidelines-php-developers-part-2-getting-rid-null

Read more

Video and slides of the 3th PHP Antwerp meetup

Yesterday our local user group, PHP Antwerp, held it's third meetup. There were two excellent speakers and a bunch of familiar faces.

Gabriel Somoza

First up was Gabriel Somoza who talked about his project Baleen. It's goal is to provide an intuitive framework to migrate almost anything. You can view his slides on Speakerdeck.

The second speaker was Marco Pivetta, better known on the interwebs as Ocramius. He is a member of the Doctrine core team. His talk was about best practices when using Doctrine. His slides can be found on GitHub. Here's the video of the talk:

https://youtu.be/j4nS_dGxxs8?t=6m44s

Spatie, of which I'm a partner, sponsored the meetup. Before Marco's talk I got the opportunity to talk a bit myself about why my company is sponsoring the local user group. My short talk can be viewed on YouTube.

The organisers announced that the next meetup will be held at the end of March. If you're living in the vicinity of Antwerp, you should definitely attend.

Read more

Everything I Needed to Know, I Learned in Rabbinical School

This Friday the PHP Benelux Conference will kick off. It has an excellent line up and I'll probably blog about the sessions I will see there.

Last year the keynote of the conference was given by Yitzchok Willroth aka Coderabbi. He emphasizes on the power of the community. It was a great talk, I even dare to use the word "inspirational". In the weeks and months after his talk numerous PHP user groups were formed in my home country, Belgium. I believe this was no coincidence.

A few days ago a video of this talk (given at another conference) was published. You can watch it below.

Read more

Writing your own test doubles

Adam Wathan posted another excellent article on testing on his blog. This time he talks about creating test doubles. Adam demonstrates that creating your own fake can result in a much more readable test than using mocks or spies.

You'll learn to create an InMemoryMailer like this:

public function test_new_users_are_sent_a_welcome_email()
{
    $mailer = new InMemoryMailer;
    Mail::swap($mailer);

    $this->post('register', [
        'name' => 'John Doe',
        'email' => 'john@example.com',
        'password' => 'secret',
    ]);

    $this->assertTrue($mailer->hasMessageFor('john@example.com'));
    $this->assertTrue($mailer->hasMessageWithSubject('Welcome to my app!'));
}

That seems like a pretty readable test to me. Read (or view) the whole tutorial here: http://adamwathan.me/2016/01/25/writing-your-own-test-doubles/

Read more

Getting rid of Laravel models to improve performance

Marko Lekić explains how he used Blackfire.io to solve a performance problem in one of his long running Laravel console commands.

The command worked, but very slowly. We left it working like that for some time until we finished critical stuff in the system and had time to go back and refactor some slow running code.

We ran the command with Blackfire.io and saw some interesting information when we ordered functions by percentage of exclusive time.

https://medium.com/@marlek/getting-rid-of-laravel-models-to-improve-performance-of-the-command-blackfire-io-profiling-53884fa6573e

Read more