Skip to content
On this page

PHP Conventions

Brackets

php
// Bad
if ($foo === 'bar')
    $response = true;
else
    $response = false;
php
// Good
if ($foo === 'bar') {
    $response = true;
} else {
    $response = false;
}

DocBlocks

Gebruik DocBlocks om je code te documenteren. Dit wordt door verschillende editors gebruikt om meer info te geven aan de developer over wat de code doet, wat de arguments zijn, welke Exceptions er worden gegooid, etc. Let wel op dat je geen nutteloze DocBlocks toevoegt

php
// Bad
/*
 * @param $view
 */
public function index($view)
{
    // Do things...
}
php
// Good
/*
 * Render the index given a specific view as a template.
 *
 * @param string $view  The name of the view to use as a template.
 * @throws ViewNotFoundException
 * @return Response
 */
public function index(string $view)
{
    // Do things...
}

Return types

Wanneer mogelijk, return types gebruiken. Op die manier weet de developer wat hij of zij zal terugkrijgen van een bepaalde method.

WARNING

Dit mag niet zomaar aangepast worden, want de kans is groot dat je dan andere code breekt!

php
// Good
public function getUser(int $id): User
{
    return User::query()->findOrFail($id); // <-- Throws Exception if not found
}

Strict Comparison

Gebruik zoveel mogelijk strict comparisons.

php
// Bad
if ($string == 'description') {
}
php
// Good
if ($string === 'description') {
}

Migrations

Gebruik migrations om aanpassingen te doen in je database, bijvoorbeeld toevoegen van tabellen of kolommen, hernoemen van kolommen, etc. Schrijf ook zoveel mogelijk rollbacks voor je migrations (down()).

Risky Migrations

Risky Migrations worden in database/risky_migrations opgeslagen zodat er een verschil is tussen de standaard migrations en de gevaarlijke migrations. De standaard migrations worden standaard uitgevoerd, de riskies kunnen worden uitgevoerd via php artisan migrate:risky.

DANGER

Risky Migrations moeten altijd een rollback (down()) hebben! Eventueel voeg je een export toe aan het begin van je migration (naar CSV bijvoorbeeld) zodat je de data kan terugzetten 'as-was'.

Happy Path

Schrijf je code volgens het Happy Path. Dus: vang alle uitzonderingen op voor de return van je method.

php
// Bad
if ($crucialThing) {
    // Do things
}

throw new Exception;
php
// Good
if (!$crucialThing) {
    throw new Exception;
}

// Do things

WARNING

Maak ook zoveel mogelijk gebruik van Custom Exceptions in plaats van de standaard Exception zodat de Developer deze op gepaste manier kan opvangen indien nodig.

No useless else

php
// Bad
if ($yay) {
    return 'yay';
} else { // <-- useless
    return 'ney';
}
php
// Good
if ($yay) {
    return 'yay';
}

return 'ney';

Type Hint Variables

Gebruik Type Hints om duidelijk te maken welke soort variables je method verwacht, zodat er geen verwarring kan ontstaan.

php
// Bad
public function calculateProfit($start, $end)
{
    // Calculate the profit
}

// Problem:
calculateProfit(1, 2);
calculateProfit('milk', 'honey');
php
// Good
public function calculateProfit(float $start, float $end)
{
    // Calculate the profit
}

Nullables op eind van arguments

php
// Bad
public function doLotsOfThings(string $method, int $number, $nullable = null, $anotherNullable = null, User $user, Company $company)
{
    // Do multiple things
}

// Dirty
doLotsOfThings('test', 1, null, null, $user, $company);
php
// Good
public function doLotsOfThings(string $method, int $number, User $user, Company $company, $nullable = null, $anotherNullable = null)
{
    // Do multiple things
}

// Clean
doLotsOfThings('test', 1, $user, $company);

Fluent Setters

Mainly for nullables.

php
// Bad
public static function createBooking(Carbon $from, Carbon $till, Room $room, $capacity, User $organizer = null, $subject = null, $external_id = null, $price = null, Customer $customer = null, $existingEvent_id = null, $replaceBooking = null, $source = null, User $creator = null, $callForCatering = null, $poNumber = null)
{
    // What am I doing with my life?
}
php
// Good
public function createBooking(Carbon $from, Carbon $till, Room $room, $capacity): RoomBooking
{
    if ($this->organizer) {
        // Organizer things...
    }
    if ($this->subject) {
        // Subject things...
    }

    // ...
}

public function setOrganizer(User $organizer): self
{
    $this->organizer = $organizer;

    return $this;
}

public function setSubject(string $subject): self
{
    $this->subject = $subject;

    return $this;
}

// Same for:
// $external_id = null
// $price = null
// Customer $customer = null
// $existingEvent_id = null
// $replaceBooking = null
// $source = null
// User $creator = null
// $callForCatering = null
// $poNumber = null

Cruddy Routes & Controllers

Hou je Routes en Controllers zo veel mogelijk cruddy en RESTful. Zo zijn deze duidelijker en voorspelbaar.

  • Url's zijn altijd meervoud en eventueel nested (/matches/{id}/events);
  • Controller methods zoveel mogelijk beperken tot index, create, store, show, update, delete (eventueel destroy als je SoftDeletes gebruikt);
    • Probeer methods zoals MatchController->updateEvent() te vermijden, maak hiervoor een nieuwe cruddy Controller MatchEventController;
  • Gebruik zoveel mogelijk FQN voor Controllers in je route files, zo worden deze ook aangepast bij een refactor (in PHPStorm);
php
// Bad
Route::get('/matches', 'MatchController@showMatches');
Route::post('/matches', 'MatchController@createMatch');
Route::get('/match/{id}', 'MatchController@showMatch');
Route::post('/match/{id}', 'MatchController@updateMatch');
php
// Good
Route::get('/matches', [MatchController::class, 'index']);
Route::post('/matches', [MatchController::class, 'store']);
Route::get('/matches/{id}', [MatchController::class, 'show']);
Route::post('/matches/{id}', [MatchController::class, 'update']);

Eloquent where clause

Altijd in een where() de operator meegeven.

php
// Bad
Model::query()->where('column', 'value')->get();
php
// Good
Model::query()->where('column', '=', 'value')->get();