PHPPHP
AdvancedLesson 16 of 16

Modern PHP: Generators, Attributes, Fibers & Tooling – PHP

Memory-friendly data streams, attributes, first-class callables, fibers and quality tools.

Generators deliver values on demand with yield. This lets you process huge files with constant memory usage.

<?php
function zeilen(string $pfad): Generator {
    $h = fopen($pfad, "r");
    try {
        while (($z = fgets($h)) !== false) {
            yield rtrim($z, "\n");
        }
    } finally {
        fclose($h);
    }
}
foreach (zeilen(__DIR__ . "/gross.log") as $nr => $zeile) {
    if (str_contains($zeile, "ERROR")) {
        echo $nr + 1, ": ", $zeile, "\n";
    }
}

function quadrate(int $bis): Generator {
    for ($i = 1; $i <= $bis; $i++) {
        yield $i => $i * $i;
    }
}
foreach (quadrate(3) as $n => $q) {
    echo "$n^2=$q ";   // 1^2=1 2^2=4 3^2=9
}

Attributes (PHP 8) attach structured metadata to classes, methods or parameters. Frameworks read them via reflection – e.g. for routing.

<?php
#[Attribute(Attribute::TARGET_METHOD)]
final class Route {
    public function __construct(public string $pfad, public string $methode = "GET") {}
}

final class HomeController {
    #[Route("/")]
    public function index(): string { return "Start"; }

    #[Route("/kontakt", methode: "POST")]
    public function kontakt(): string { return "Thanks"; }
}

foreach ((new ReflectionClass(HomeController::class))->getMethods() as $m) {
    foreach ($m->getAttributes(Route::class) as $attr) {
        $route = $attr->newInstance();
        echo $route->methode, " ", $route->pfad, " -> ", $m->getName(), "\n";
    }
}

More means of expression: the nullsafe operator ?->, first-class callables (strlen(...)) and fibers for cooperative multitasking (the foundation of async libraries like Revolt or Amp).

<?php
class Adresse { public function __construct(public ?string $stadt = null) {} }
class Nutzer { public function __construct(public ?Adresse $adresse = null) {} }

$u = new Nutzer();
echo $u->adresse?->stadt ?? "unknown", "\n";   // unknown

$laenge = strlen(...);
echo $laenge("abc"), "\n";                       // 3

$fiber = new Fiber(function (): void {
    $x = Fiber::suspend("paused");
    echo "continuing with $x\n";
});
echo $fiber->start(), "\n";     // paused
$fiber->resume("Data");        // continuing with Data

Professionally, you work with tools that find errors before users see them:

  • PHPUnit / Pest for automated tests
  • PHPStan or Psalm for static analysis (type errors without running the code)
  • PHP-CS-Fixer / PHP_CodeSniffer for consistent style according to PSR-12
  • OPcache stores compiled bytecode – a must in production for speed
  • Xdebug for debugging and profiling
<?php
use PHPUnit\Framework\TestCase;
use App\Service\Rechner;

final class RechnerTest extends TestCase {
    public function testAddition(): void {
        $this->assertSame(5, (new Rechner())->addiere(2, 3));
    }
}
TipFrameworks take a lot of work off your hands: Laravel (routing, Eloquent ORM, queues) and Symfony (reusable components) are built on exactly these concepts: namespaces, Composer, interfaces, attributes and dependency injection.