RDM LABSPORTUGUÊS

Technical article/ · 7 min read

Modern PHP: the language Laravel 13 demands

Laravel Saga · Season 0 · Episode 04

Let me guess: at some point in your life, someone told you PHP is a messy language, full of files mixing HTML with mysql_query(). And, to be honest, there was a time when that reputation had some basis.

But that time is long gone. Today's PHP has a robust type system, enums, read-only properties, attributes and an introspection API that lets frameworks like Laravel "read" your code and act on it.

In this episode, I won't try to cover the whole language. I'll focus on the features that show up all the time in Laravel 13, which requires PHP 8.3 or higher. And, at the end, I want to show you the feature that, for me, is the key to understanding half of the framework's "magic".

Types: code that explains itself

Let's start with an example you could find in any serious project:

php<?php

declare(strict_types=1);

final class Money
{
    public function __construct(
        public readonly int $amount,       // in cents
        public readonly string $currency,
    ) {}

    public function add(Money $other): Money
    {
        if ($other->currency !== $this->currency) {
            throw new InvalidArgumentException('Different currencies.');
        }

        return new Money($this->amount + $other->amount, $this->currency);
    }
}

Notice how, at a glance, you already know what goes into and comes out of each method. PHP today offers types for practically any situation:

FeatureExampleSince
Scalar and return typesfunction total(int $a): int7.0
Nullable?User $user7.1
Typed propertiesprivate string $name;7.4
Union typesint|string $id8.0
mixedmixed $value8.0
neverfunction fail(): never8.1
IntersectionCountable&Iterator $items8.1
DNF types(A&B)|null8.2
Typed class constantsconst string VERSION = '1.0';8.3

What about that declare(strict_types=1)?

Without that line, PHP tries to convert types on its own: if you pass the string "5" to an int parameter, it silently accepts it. With it, PHP throws a TypeError. Worth knowing: this declaration works per file and affects the calls made from that file.

And here's a point I want you to remember: types aren't just for PHP. They're what let Laravel's container know what to inject into each parameter. Towards the end of the episode, you'll see exactly how.

Constructor promotion and readonly

Before PHP 8.0, writing a simple class meant repeating each property three times. Look at the difference:

php// Before
class CreateUser
{
    private UserRepository $users;
    private Hasher $hasher;

    public function __construct(UserRepository $users, Hasher $hasher)
    {
        $this->users = $users;
        $this->hasher = $hasher;
    }
}

// After (8.0+)
class CreateUser
{
    public function __construct(
        private UserRepository $users,
        private Hasher $hasher,
    ) {}
}

That second form is exactly what you'll find in Laravel services, actions and controllers. It's worth getting used to it.

readonly properties, which arrived in 8.1, can only be written once, from inside the class. And from 8.2 you can mark the whole class:

phpfinal readonly class Address
{
    public function __construct(
        public string $street,
        public string $city,
        public string $zipCode,
    ) {}
}

$address = new Address('Rua A', 'Recife', '50000-000');
$address->city = 'Olinda'; // Error: Cannot modify readonly property

It may look like an annoying restriction, but think about what it prevents: nobody can change this object "behind your back". Immutable objects eliminate a whole category of bugs.

Enums: goodbye, magic strings

How many times have you seen a status stored as a string and a bug caused by a mistyped 'publised'? Before PHP 8.1, we made do with loose constants. Now there are real enums:

phpenum PostStatus: string
{
    case Draft = 'draft';
    case Published = 'published';
    case Archived = 'archived';

    public function label(): string
    {
        return match ($this) {
            self::Draft => 'Draft',
            self::Published => 'Published',
            self::Archived => 'Archived',
        };
    }

    public function isVisible(): bool
    {
        return $this === self::Published;
    }
}

$status = PostStatus::from('published');  // PostStatus::Published
$status = PostStatus::tryFrom('xyz');     // null
PostStatus::cases();                      // every case

Notice that an enum can have methods, which lets you keep the rule next to the concept. And Laravel has embraced enums in several places: in model casts (the status column arrives as a PostStatus), in validation (Rule::enum(PostStatus::class)) and in routes (an invalid value in the URL automatically produces a 404).

match, nullsafe and named arguments

Three small features that make code much cleaner:

php// match: strict comparison (===), returns a value and complains if a case is missing
$fee = match (true) {
    $total >= 50000 => 0,
    $total >= 10000 => 990,
    default => 1990,
};

// nullsafe: stops the chain at the first null
$city = $order?->customer?->address?->city;

// named arguments: clarity and freedom of order
$code = str_pad(string: '7', length: 3, pad_string: '0', pad_type: STR_PAD_LEFT);

Named arguments, in particular, show up a lot in Laravel 13's configuration APIs, as in Application::configure(basePath: ...) and Queue::route(Job::class, connection: 'redis', queue: 'podcasts').

Closures, arrow functions and callables

If there's one thing Laravel uses everywhere, it's anonymous functions: in routes, collections, events, middleware.

php$rate = 0.1;

// Classic closure: needs use to capture outside variables
$withFee = function (int $value) use ($rate) {
    return $value * (1 + $rate);
};

// Arrow function (7.4+): captures on its own, but accepts a single expression
$withFee = fn (int $value) => $value * (1 + $rate);

// First-class callable (8.1+): turns a function into a closure
$upper = array_map(strtoupper(...), ['a', 'b']);
$validate = $this->validate(...);

The detail that makes all the difference: a closure keeps the context it was created in. It can be passed around and run much later. That's what makes it possible to write something like Route::get('/', fn () => view('home')): you're handing the framework a function for it to call when the time comes.

Recent additions worth knowing

You don't need to use all of this to work with Laravel 13, but you'll bump into these features in packages and in modern code.

PHP 8.3

phpclass Plugin extends BasePlugin
{
    const string VERSION = '2.0';   // typed constant

    #[\Override]                    // error if the method doesn't exist in the parent class
    public function boot(): void {}
}

json_validate('{"ok": true}');      // validates JSON without decoding it

PHP 8.4

phpclass User
{
    // Property hooks: read/write logic on the property itself
    public string $email {
        set => strtolower(trim($value));
    }

    // Asymmetric visibility: public read, private write
    public private(set) int $loginCount = 0;
}

// new without extra parentheses
$email = new User()->email;

PHP 8.5

php// Pipe operator: chains functions from left to right
$slug = '  Hello World  '
    |> trim(...)
    |> strtolower(...)
    |> (fn ($s) => str_replace(' ', '-', $s));

Attributes: metadata inside the code

And now, the feature I promised at the start. If you want to understand Laravel 13, you need to understand attributes.

An attribute, available since PHP 8.0, is a piece of metadata you attach to classes, methods, properties, parameters or constants, using the #[...] syntax. And here's the point almost nobody explains properly: on its own, an attribute does absolutely nothing. It only takes effect when some code goes and reads it.

phpuse Attribute;

#[Attribute(Attribute::TARGET_CLASS)]
final class Table
{
    public function __construct(public string $name) {}
}

#[Table('blog_posts')]
class Post {}

In Laravel 13, you'll see attributes everywhere: #[Table], #[Fillable] and #[Hidden] on models; #[Middleware] and #[Authorize] on controllers; #[Tries] and #[Timeout] on jobs; #[Config] and #[CurrentUser] on the parameters the container injects.

And the natural question is: if an attribute does nothing on its own, who reads all of them? The answer is the Reflection API.

Reflection: code that looks at its own code

Reflection lets a program examine its own structure while it runs. With it, you find out which methods a class has, which parameters and types each method receives and which attributes are attached to each thing.

Reading the attribute from the previous example:

php$reflection = new ReflectionClass(Post::class);

foreach ($reflection->getAttributes(Table::class) as $attribute) {
    $table = $attribute->newInstance();
    echo $table->name; // blog_posts
}

Now pay attention to this next example, because it's the heart of the episode. See how to find out what a constructor needs:

phpclass CreateUser
{
    public function __construct(
        private UserRepository $users,
        private Hasher $hasher,
    ) {}
}

$constructor = (new ReflectionClass(CreateUser::class))->getConstructor();

foreach ($constructor->getParameters() as $parameter) {
    echo $parameter->getName() . ': ' . $parameter->getType() . PHP_EOL;
}

// users: UserRepository
// hasher: Hasher

Do you see what that means? If a program can find out that CreateUser needs a UserRepository and a Hasher, it can create those dependencies on its own and assemble the whole object. That's the autowiring of Laravel's Service Container. There's no magic at all: there's Reflection reading the types you declared.

To wrap up, let's put the two pieces together. This is a mini "framework" that reads attributes and creates routes:

php#[Attribute(Attribute::TARGET_METHOD)]
final class Route
{
    public function __construct(public string $method, public string $path) {}
}

class PostController
{
    #[Route('GET', '/posts')]
    public function index(): string
    {
        return 'List of posts';
    }
}

$routes = [];

foreach ((new ReflectionClass(PostController::class))->getMethods() as $method) {
    foreach ($method->getAttributes(Route::class) as $attribute) {
        $route = $attribute->newInstance();
        $routes["{$route->method} {$route->path}"] = [PostController::class, $method->getName()];
    }
}

[$class, $action] = $routes['GET /posts'];
echo (new $class)->$action(); // List of posts

That's about 25 lines, and you have attribute-based routing working. Run it on your machine. Laravel does this with much more care (and with caching), but the principle is exactly the same.

Who reads what you declared#[Route] to Reflection API: getAttributes(). Constructor types to Reflection API: getParameters(). Reflection API to Route table: registers the route. Reflection API to Container: autowiring. Scenario Attributes. On its own,. Path: #[Route], Reflection API, Route table. Scenario Autowiring. Reflection reads the constructor's types and the container creates a UserRepository and a Hasher before assembling CreateUser. Path: Constructor types, Reflection API, Container.#[Route]metadata on the methodConstructor typesUserRepository, HasherReflection APIreads the running codeRoute tableGET /postsContainercreates the dependenciesgetAttributes()getParameters()registers the routeautowiring#[Route]metadata on the methodReflection APIreads the running codeRoute tableGET /postsgetAttributes()registers the routeConstructor typesUserRepository, HasherReflection APIreads the running codeContainercreates the dependenciesgetParameters()autowiring
Who reads what you declared#[Route] to Reflection API: getAttributes(). Constructor types to Reflection API: getParameters(). Reflection API to Route table: registers the route. Reflection API to Container: autowiring. Scenario Attributes. On its own,. Path: #[Route], Reflection API, Route table. Scenario Autowiring. Reflection reads the constructor's types and the container creates a UserRepository and a Hasher before assembling CreateUser. Path: Constructor types, Reflection API, Container.#[Route]metadata on the methodConstructor typesUserRepository, HasherReflection APIreads the running codeRoute tableGET /postsContainercreates the dependenciesgetAttributes()getParameters()registersautowiring#[Route]metadata on the methodReflection APIreads the running codeRoute tableGET /postsgetAttributes()registersConstructor typesUserRepository, HasherReflection APIreads the running codeContainercreates the dependenciesgetParameters()autowiring

Attributes

On its own,

Autowiring

Reflection reads the constructor's types and the container creates a UserRepository and a Hasher before assembling CreateUser.

Who reads what you declared

What to take into the saga

  • Types document the code and let the framework know what to inject.
  • Constructor promotion and readonly keep services and value objects lean and safe.
  • Enums replace magic strings and integrate with casts, validation and routes.
  • Attributes are metadata; on their own, they do nothing.
  • Reflection is what reads types and attributes, and it's the engine behind autowiring and Laravel 13's #[...].

Next episode

Our code now uses classes like UserRepository and Hasher. But have you ever stopped to think about how PHP finds the file for each of them? And how is it possible to use thousands of packages written by different people without copying and pasting code?

In the next episode, we'll talk about Composer, autoloading and the PSRs, the standards that make the PHP ecosystem work as one. See you in episode 05.

References and further reading

Official documentation

Going deeper