php
Modern PHP programming patterns
What this skill does
# PHP
## Overview
Modern PHP (7.4+/8.x) patterns including typed properties, attributes, and modern OOP features.
---
## Modern PHP Features
### Type System
```php
<?php
declare(strict_types=1);
// Typed properties (PHP 7.4+)
class User
{
public string $id;
public string $email;
public ?string $name = null;
public bool $active = true;
public array $roles = [];
public DateTimeImmutable $createdAt;
// Constructor promotion (PHP 8.0+)
public function __construct(
public readonly string $email,
public readonly string $name,
private string $password
) {
$this->id = uniqid();
$this->createdAt = new DateTimeImmutable();
}
}
// Union types (PHP 8.0+)
function process(string|int $value): string|int
{
return is_string($value) ? strtoupper($value) : $value * 2;
}
// Intersection types (PHP 8.1+)
function processIterable(Countable&Iterator $items): int
{
return count($items);
}
// Return types
function findUser(string $id): ?User
{
return $this->repository->find($id);
}
function getUsers(): array
{
return $this->repository->findAll();
}
// Never return type (PHP 8.1+)
function fail(string $message): never
{
throw new RuntimeException($message);
}
// Nullable types
function setName(?string $name): void
{
$this->name = $name;
}
```
### Attributes (PHP 8.0+)
```php
<?php
use Attribute;
// Define 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(
public string $table
) {}
}
// Using attributes
#[Entity(table: 'users')]
class User
{
#[Column(name: 'id', type: 'uuid')]
public string $id;
#[Column(name: 'email', type: 'string')]
public string $email;
#[Column(name: 'name', nullable: true)]
public ?string $name;
}
class UserController
{
#[Route(path: '/users', method: 'GET')]
public function index(): array
{
return $this->userService->getAll();
}
#[Route(path: '/users/{id}', method: 'GET')]
public function show(string $id): User
{
return $this->userService->find($id);
}
}
// Reading attributes
$reflection = new ReflectionClass(User::class);
$attributes = $reflection->getAttributes(Entity::class);
foreach ($attributes as $attribute) {
$instance = $attribute->newInstance();
echo $instance->table; // 'users'
}
```
### Enums (PHP 8.1+)
```php
<?php
// Basic enum
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',
};
}
}
// Backed enum (with values)
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 => ['read', 'write', 'delete'],
self::User => ['read', 'write'],
};
}
public static function fromString(string $value): self
{
return self::from($value);
}
public static function tryFromString(string $value): ?self
{
return self::tryFrom($value);
}
}
// Usage
$status = Status::Active;
echo $status->label(); // "Active"
$role = Role::Admin;
echo $role->value; // "admin"
$userRole = Role::from('user');
$permissions = $userRole->permissions();
```
---
## Object-Oriented Patterns
### Traits
```php
<?php
// Trait definition
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 DateTimeImmutable();
}
public function restore(): void
{
$this->deletedAt = null;
}
public function isDeleted(): bool
{
return $this->deletedAt !== null;
}
}
// Using traits
class Document
{
use Timestampable;
use SoftDeletable;
public function __construct(
public string $title,
public string $content
) {
$this->touch();
}
}
// Trait conflict resolution
trait A
{
public function hello(): string
{
return 'Hello from A';
}
}
trait B
{
public function hello(): string
{
return 'Hello from B';
}
}
class MyClass
{
use A, B {
A::hello insteadof B;
B::hello as helloFromB;
}
}
```
### Interfaces and Abstract Classes
```php
<?php
// Interface
interface Repository
{
public function find(string $id): ?object;
public function findAll(): array;
public function save(object $entity): void;
public function delete(string $id): void;
}
// Generic-style interface
interface Collection
{
public function add(mixed $item): void;
public function remove(mixed $item): bool;
public function contains(mixed $item): bool;
public function count(): int;
public function toArray(): array;
}
// Abstract class
abstract class BaseRepository implements Repository
{
public function __construct(
protected PDO $pdo,
protected string $table
) {}
abstract protected function hydrate(array $row): object;
public function find(string $id): ?object
{
$stmt = $this->pdo->prepare(
"SELECT * FROM {$this->table} WHERE id = :id"
);
$stmt->execute(['id' => $id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return $row ? $this->hydrate($row) : null;
}
public function findAll(): array
{
$stmt = $this->pdo->query("SELECT * FROM {$this->table}");
return array_map(
fn(array $row) => $this->hydrate($row),
$stmt->fetchAll(PDO::FETCH_ASSOC)
);
}
}
// Concrete implementation
class UserRepository extends BaseRepository
{
public function __construct(PDO $pdo)
{
parent::__construct($pdo, 'users');
}
protected function hydrate(array $row): User
{
return new User(
id: $row['id'],
email: $row['email'],
name: $row['name']
);
}
public function findByEmail(string $email): ?User
{
// Custom method
}
}
```
---
## Error Handling
```php
<?php
// Custom exceptions
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
);
}
}
class NotFoundException extends AppException
{
public function __construct(
string $resource,
string $id,
?ThrowableRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.