Sort an array by object attribute in PHP

One of those simple things that I keep forgetting.

Suppose you have to sort a set of PHP objects, based on an attribute.

To do this, you can implement the __toString method and use the SORT_STRING flag in the sort function:

<?php

class Car {
    private $_maker;

    public function __construct( $maker ) {
        $this->maker = $maker;
    }


    public function __toString() {
        return $this->maker;
    }
}

$car1 = new Car( 'BMW' );
$car2 = new Car( 'Alfa Romeo' );
$car3 = new Car( 'Volvo' );

$cars   = [];
$cars[] = $car1;
$cars[] = $car2;
$cars[] = $car3;

// sort the array
sort( $cars, SORT_STRING );

var_dump( $cars );

This will result in:

/*
==RESULT== 
array(3) {
  [0]=>
  object(Car)#2 (2) {
    ["_maker":"Car":private]=>
    NULL
    ["maker"]=>
    string(10) "Alfa Romeo"
  }
  [1]=>
  object(Car)#1 (2) {
    ["_maker":"Car":private]=>
    NULL
    ["maker"]=>
    string(3) "BMW"
  }
  [2]=>
  object(Car)#3 (2) {
    ["_maker":"Car":private]=>
    NULL
    ["maker"]=>
    string(5) "Volvo"
  }
}
 */

Set Ubuntu desktop background from Unsplash

I love having inspiring desktop background while I work. Often I leave a monitor free of anything, just to admire a wonderful photo.

Unsplash is the perfect source for free stock photos, so I thought to set up a script to fetch a random image from Unsplash and set it as the desktop background on Ubuntu.

I was going to create a custom PHP application, but then I found Unsplash.it so I created this simple bash script:

#/bin/bash

wget -O /tmp/wallpaper.jpg https://unsplash.it/2560/1440/?random
gsettings set org.gnome.desktop.background picture-uri file:///tmp/wallpaper.jpg

You can put this in your ~/bin/ folder, or set a crontab to change it automatically for you.

Don’t collapse File headers by default in PHPStorm

By default PHPStorm (which I love, BTW) collapses header comments. I think this is not a safe default, as I use header comment to give my fellow developers (or my future self) an overview about the file they’re going to read.

To deactivate this behavior, just go to Settings > Editor > General > Code Folding and uncheck File Header

Do you ask for code reviews?

Lately I find myself asking for code reviews more often. I used to think exactly as Wiegers put it:

Anyone who needs his code reviewed shouldn’t be getting paid as a software developer

But that’s not true. Code reviews improve code quality a lot! And, as a side effect, they improve also team cohesion.

So read “Who’s Your Coding Buddy?” via Coding Horror