PHP 8.3: Développement Backend Moderne et Performant
PHP a évolué pour devenir un langage moderne et performant. Découvrez les dernières features.
Setup et Configuration
# Vérifier la version
php -v
# Serveur de développement
php -S localhost:8000
# Mode strict (recommandé)
declare(strict_types=1);
Types et Type Hints
<?php
declare(strict_types=1);
// Types primitifs
function addNumbers(int $a, int $b): int {
return $a + $b;
}
// Types nullables
function getName(?string $name): ?string {
return $name ?? "Anonymous";
}
// Types union (PHP 8.0+)
function process(int|string $value): string {
return match(gettype($value)) {
'integer' => "Nombre: $value",
'string' => "Texte: $value",
};
}
// Types mixed
function handleAny(mixed $value): mixed {
return $value;
}
// Array types
function processArray(array $items): array {
return array_map(fn($item) => $item * 2, $items);
}
Match Expressions (PHP 8.0+)
// Bien mieux que switch!
$role = 'admin';
$message = match($role) {
'admin' => 'Vous avez un accès complet',
'user' => 'Accès utilisateur standard',
'guest' => 'Accès limité',
default => 'Rôle inconnu',
};
Attributes (PHP 8.0+)
// Définir un attribute
#[Attribute]
class Route {
public function __construct(
public string $method,
public string $path,
) {}
}
// L'utiliser
#[Route('GET', '/posts')]
class PostController {
#[Route('POST', '/posts')]
public function store() {
// ...
}
}
// Récupérer les attributes
$reflection = new ReflectionClass(PostController::class);
$attributes = $reflection->getAttributes(Route::class);
Constructors Promotion (PHP 8.0+)
// ❌ Ancien style
class User {
public string $name;
public string $email;
public function __construct(string $name, string $email) {
$this->name = $name;
$this->email = $email;
}
}
// ✅ Nouveau style (8.0+)
class User {
public function __construct(
public string $name,
public string $email,
) {}
}
Named Arguments (PHP 8.0+)
function createUser(string $name, string $email, string $role = 'user') {
// ...
}
// Ancien style
createUser('Jean', 'jean@example.com', 'admin');
// Nouveau style (plus clair!)
createUser(
name: 'Jean',
email: 'jean@example.com',
role: 'admin',
);
// Ordre différent aussi possible
createUser(
email: 'jean@example.com',
name: 'Jean',
role: 'admin',
);
Arrow Functions (PHP 7.4+)
// Fonction normale
$multiply = function($a, $b) {
return $a * $b;
};
// Arrow function (plus concis)
$multiply = fn($a, $b) => $a * $b;
// Avec array_map
$numbers = [1, 2, 3, 4];
$squared = array_map(fn($n) => $n * $n, $numbers);
// [1, 4, 9, 16]
// Avantages:
// - Syntaxe plus courte
// - Bind automatique à $this
// - Une expression seulement
Gestion d'Erreurs Moderne
try {
if (!$user) {
throw new InvalidArgumentException('User not found');
}
$result = processUser($user);
} catch (InvalidArgumentException $e) {
logger()->error('Invalid argument: ' . $e->getMessage());
return response()->json(['error' => 'Invalid input'], 400);
} catch (Exception $e) {
logger()->critical('Unexpected error: ' . $e);
return response()->json(['error' => 'Server error'], 500);
} finally {
// Toujours exécuté
logger()->info('Operation completed');
}
// Custom Exceptions
class UserNotFoundException extends Exception {}
try {
$user = User::findOrFail($id);
} catch (UserNotFoundException $e) {
// Traiter spécifiquement
}
Namespaces et Autoloading
<?php
namespace App\Models;
class User {
// ...
}
// Utilisation
namespace App\Controllers;
use App\Models\User;
class UserController {
public function show($id) {
$user = User::find($id);
}
}
// composer.json
{
"autoload": {
"psr-4": {
"App\\": "app/"
}
}
}
Performance Tips
// 1. Utiliser les types (plus rapide)
function process(array $items): array {
// Type checking automatique
}
// 2. Cache les résultats
$cache = [];
if (!isset($cache[$key])) {
$cache[$key] = expensiveOperation();
}
// 3. Utiliser prepared statements
$pdo = new PDO('sqlite::memory:');
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
// 4. Lazy loading
$user = User::find(1);
$posts = $user->posts()->get(); // Charge au besoin
// 5. Optimiser les boucles
foreach ($items as &$item) {
$item['processed'] = true;
}
unset($item); // Libérer la référence
Ressources
PHP.net: https://www.php.net
PHP FIG: https://www.php-fig.org
Packagist: https://packagist.org
Aucun commentaire pour le moment. Soyez le premier !