PHP Typing with Laravel: Writing Clean, Robust Code

#Laravel #typing #strict typing #laravel best practices #improving typing #typing in laravel #typing in php

3 min read.

PHP Typing with Laravel: Writing Clean, Robust Code
Hamdaoui Wassim Avatar

Hamdaoui Wassim

0
0

PHP has evolved significantly from its early days as a simple scripting language. One of the most impactful changes since PHP 7 has been the introduction and expansion of type declarations. When combined with modern frameworks like Laravel, typing can significantly improve code quality, reduce bugs, and enhance developer productivity.

In this article, we’ll explore how PHP's typing works and how Laravel leverages it for clean, maintainable applications.

 

Understanding PHP Typing :

PHP typing comes in several forms:

1. Scalar Type Declarations :

Introduced in PHP 7, this allows specifying types for function parameters and return values.

<?php

function multiply(int $a, int $b): int {
    return $a * $b;
}


?>

2. Nullable Types :

Use a ? before the type to allow null as a value.

<?php

function findUser(?int $id): ?User {
    // logic
}


?>

3. Union Types (PHP 8.0+) :

Allow multiple types.

<?php

function formatDate(string|DateTime $date): string {
    // logic
}



?>

4. Intersection Types (PHP 8.1+) :

Allow specifying multiple interfaces a type must implement.

<?php

function process(LoggerInterface&ArrayAccess $object) {
    // logic
}



?>

4. Readonly Properties (PHP 8.1+) :

Immutable properties after initialization.

<?php

class User {
    public readonly int $id;

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



?>

 

How Laravel Uses Typing :

Laravel, being a modern PHP framework, embraces typing to the fullest across its codebase.

1. Constructor Injection with Typed Services :

Laravel’s service container uses type hints to resolve dependencies automatically.

<?php

class UserController extends Controller
{
    public function __construct(private UserService $userService) {}
}

?>

2. Route Model Binding with Type Hints :

Laravel uses type hints in controllers for automatic model resolution.

<?php

public function show(User $user)
{
    return view('users.show', compact('user'));
}


?>

3. Form Request Validation :

Custom request classes leverage type hints for cleaner method signatures:

<?php

public function store(CreatePostRequest $request)
{
    $validated = $request->validated();
}


?>

4. Custom Commands & Event Listeners :

Commands and listeners also benefit from type safety, improving IDE support and preventing bugs.

<?php

public function handle(SendWelcomeEmail $event)
{
    Mail::to($event->user)->send(new WelcomeEmail());
}


?>

Benefits of Typing in Laravel :

  • Better IDE support: Type hints enable autocompletion and static analysis.

  • Fewer bugs: Type mismatches are caught earlier.

  • Improved readability: Method signatures become self-documenting.

  • Easier testing and refactoring: Typed code is more predictable.

Best Practices :

  • Use return types for all methods, especially in services and repositories.

  • Use @var and @property in PHPDoc where PHP doesn’t support typing (e.g., dynamic properties).

  • Combine PHP typing with Laravel's validation—type hints ensure structure, validation ensures content.

 

Example: Typed Service in Laravel :

<?php


namespace App\Services;

use App\Models\User;

class UserService
{
    public function createUser(string $name, string $email): User
    {
        return User::create([
            'name' => $name,
            'email' => $email,
        ]);
    }
}

?>

Injected into a controller:

<?php

public function store(Request $request, UserService $userService): JsonResponse
{
    $user = $userService->createUser($request->name, $request->email);
    return response()->json($user);
}


?>

Tools to Improve Typing :

  • PHPStan / Psalm: Static analysis tools to enforce typing and catch issues.

  • PHP Intelephense: A popular VSCode extension for intelligent code completion.

  • Larastan: Laravel-focused wrapper around PHPStan.

Conclusion :

Typing in PHP, especially when used with Laravel, is a powerful tool that leads to more maintainable, secure, and efficient codebases. Laravel's design encourages typing best practices, allowing developers to write expressive, readable, and robust applications.

Start adding types to your Laravel projects today—you’ll thank yourself later.

0 Comments