Be careful with type hinting & strict types when you fetch numbers from Redis

One tricky thing that we should be aware of, when it comes to retrieving numbers from Redis, using Laravel is that the retrieved value will be a string.

That can cause some unexpected problems, let me show you below an example.

Let's say that we have this dummy service.

<?php

declare(strict_types=1);

namespace App\Services;

use Illuminate\Support\Facades\Cache;

class SomeService
{
    public function cacheNumber(int $number): void
    {
        Cache::set('myNumber', $number);
    }

    public function getNumberFromCache(): int
    {
        return Cache::get('myNumber');
    }
}

Note the strict_types=1 on the top. It's important. This is considered as a good practice in general, so nothing weird here.

And let's pretend that we use the service somewhere in our code:

$service->cacheNumber(50);
$number = $service->getNumberFromCache();

We expect the $number variable to be 50, but that's not gonna happen.

Instead we get a TypeError exception! Ouch!

App\Services\SomeService::getNumberFromCache(): Return value must be of type int, string returned

Remember, Redis will return numeric values as string to your Laravel application!

And the problem happens in:

public function getNumberFromCache(): int
{
    return Cache::get('myNumber');
}

This is being translated into:

public function getNumberFromCache(): int
{
    return "50";
}

And in combination with strict_types=1, PHP expects you to return the correct type. It won't automatically convert "50" to 50.

To fix it, we could cast the result to make sure that we will return an integer:

public function getNumberFromCache(): int
{
    return (int) Cache::get('myNumber');
    // translates to: (int) "50" which is 50
}

Tricky one, right? Be aware :)

Subscribe to Lioy

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe