| name | php |
| description | Modern PHP programming patterns |
| domain | programming-languages |
| version | 1.0.0 |
| tags | ["php","laravel","composer","oop","traits"] |
| triggers | {"keywords":{"primary":["php","laravel","composer","symfony","wordpress"],"secondary":["eloquent","blade","artisan","phpunit","trait","doctrine"]},"context_boost":["web","backend","cms","api","legacy"],"context_penalty":["python","javascript","java","go"],"priority":"medium"} |
PHP
Overview
Modern PHP (7.4+/8.x) patterns including typed properties, attributes, and modern OOP features.
Modern PHP Features
Type System
<?php
declare(strict_types=1);
class User
{
public string $id;
public string $email;
public ?string $name = null;
public bool $active = true;
public array $roles = [];
public DateTimeImmutable $createdAt;
public function __construct(
public readonly string $email,
public readonly string $name,
private string $password
) {
$this->id = uniqid();
$this->createdAt = new DateTimeImmutable();
}
}
function process(string|int $value): string|int
{
return is_string($value) ? strtoupper($value) : $value * 2;
}
function processIterable(Countable&Iterator $items): int
{
return count($items);
}
function findUser(string $id): ?User
{
return $this->repository->find($id);
}
function getUsers(): array
{
return $this->repository->findAll();
}
function fail(string $message): never
{
throw new RuntimeException($message);
}
function setName(?string $name): void
{
$this->name = $name;
}
Attributes (PHP 8.0+)
<?php
use Attribute;
#[Attribute(Attribute::TARGET_PROPERTY)]
class Column
{
public function __construct(
public string $name,
public string $type = 'string',
public bool $nullable = false
) {}
}
#[Attribute(Attribute::TARGET_METHOD)]
class Route
{
public function __construct(
public string $path,
public string $method = 'GET'
) {}
}
#[Attribute(Attribute::TARGET_CLASS)]
class Entity
{
public function __construct() {}
}
(: )
{
(: , : )
;
(: , : )
;
(: , : )
? ;
}
{
(: , : )
{
->userService->();
}
(: , : )
{
->userService->();
}
}
= (::);
= ->(::);
( ) {
= ->();
->table;
}
Enums (PHP 8.1+)
<?php
enum Status
{
case Pending;
case Active;
case Inactive;
public function label(): string
{
return match ($this) {
self::Pending => 'Pending Review',
self::Active => 'Active',
self::Inactive => 'Inactive',
};
}
}
enum Role: string
{
case Admin = 'admin';
case Moderator = 'moderator';
case User = 'user';
public function permissions(): array
{
return match ($this) {
self::Admin => ['read', 'write', 'delete', 'admin'],
self::Moderator => [, , ],
:: => [, ],
};
}
{
::();
}
{
::();
}
}
= ::;
->();
= ::;
->value;
= ::();
= ->();
Object-Oriented Patterns
Traits
<?php
trait Timestampable
{
protected ?DateTimeImmutable $createdAt = null;
protected ?DateTimeImmutable $updatedAt = null;
public function getCreatedAt(): ?DateTimeImmutable
{
return $this->createdAt;
}
public function getUpdatedAt(): ?DateTimeImmutable
{
return $this->updatedAt;
}
public function touch(): void
{
$now = new DateTimeImmutable();
$this->createdAt ??= $now;
$this->updatedAt = $now;
}
}
trait SoftDeletable
{
protected ?DateTimeImmutable $deletedAt = null;
public function delete(): void
{
$this->deletedAt = new ();
}
{
->deletedAt = ;
}
{
->deletedAt !== ;
}
}
{
;
;
{
->();
}
}
{
{
;
}
}
{
{
;
}
}
{
, {
:: ;
B:: helloFromB;
}
}
Interfaces and Abstract Classes
<?php
interface Repository
{
public function find(string $id): ?object;
public function findAll(): array;
public function save(object $entity): void;
public function delete(string $id): void;
}
interface Collection
{
public function add(mixed $item): void;
public function remove(mixed $item): bool;
public function contains(mixed $item): ;
;
;
}
{
{}
;
{
= ->pdo->(
);
->([ => ]);
= ->(PDO::);
? ->() : ;
}
{
= ->pdo->();
(
fn( ) => ->(),
->(PDO::)
);
}
}
{
{
::(, );
}
{
(
id: [],
email: [],
name: []
);
}
{
}
}
Error Handling
<?php
class AppException extends Exception
{
public function __construct(
string $message,
public readonly string $code,
public readonly array $context = [],
?Throwable $previous = null
) {
parent::__construct($message, 0, $previous);
}
}
class ValidationException extends AppException
{
public function __construct(
public readonly array $errors,
?Throwable $previous = null
) {
parent::__construct(
'Validation failed',
'VALIDATION_ERROR',
['errors' => $errors],
$previous
);
}
}
{
{
::(
,
,
[ => , => ],
);
}
}
{
{}
{
(, , );
}
{
(, , );
}
{
(!->success) {
;
}
::((->value));
}
{
(!->success) {
;
}
(->value);
}
}
{
(([])) {
::();
}
{
= ([], [] ?? );
->repository->();
::();
} ( ) {
::(->());
}
}
Collections and Arrays
<?php
$users = [
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
['name' => 'Charlie', 'age' => 35],
];
$adults = array_filter($users, fn($u) => $u['age'] >= 30);
$names = array_map(fn($u) => $u['name'], $users);
$totalAge = array_reduce($users, fn($sum, $u) => $sum + $u['age'], 0);
$bob = array_filter($users, fn($u) => $u['name'] === 'Bob');
$bob = current($bob);
usort(, fn(, ) => [] <=> []);
{
(, function (, ) ($) {
$[$[$]][] = $;
;
}, []);
}
{
{}
{
();
}
{
((, ->items));
}
{
((->items, ));
}
{
(->items, , );
}
{
->items[(->items)] ?? ;
}
{
(->items);
}
{
(->items);
}
{
->items;
}
}
= ::()
->(fn() => [] >= )
->(fn() => [])
->();
Dependency Injection
<?php
interface LoggerInterface
{
public function info(string $message, array $context = []): void;
public function error(string $message, array $context = []): void;
}
interface UserRepositoryInterface
{
public function find(string $id): ?User;
public function save(User $user): void;
}
class UserService
{
public function __construct(
private readonly UserRepositoryInterface $repository,
private readonly LoggerInterface $logger,
EventDispatcher
) {}
{
->logger->(, [ => ]);
= (, );
->repository->();
->events->( ());
;
}
}
{
= [];
= [];
{
->bindings[] = ;
}
{
->bindings[] = {
(!(->instances[])) {
->instances[] = ();
}
->instances[];
};
}
{
((->bindings[])) {
->bindings[]();
}
->();
}
{
= ();
= ->();
(!) {
();
}
= (
fn(ReflectionParameter ) => ->(->()->()),
->()
);
->();
}
}
Related Skills
- [[backend]] - Laravel, Symfony
- [[database]] - Doctrine, Eloquent
- [[testing]] - PHPUnit, Pest