Willkommen

Im Internet kursieren viele veraltete Informationen, die PHP-Anfänger verwirren und so zu schlechten Praktiken und unsicherem Code führen. PHP - aber richtig ist ein leicht verständliches Nachschlagewerk zu gängigen PHP-Programmierstandards, Links zu maßgeblichen Tutorials im Internet und Informationen zu den aktuellen Best-Practices der Autoren.

Es gibt keine allgemeingültige Herangehensweise PHP zu verwenden. Diese Website möchte PHP-Anfängern Themen näherbringen, die sie möglicherweise erst entdecken, wenn es zu spät ist, und erfahrenen Profis neue Ideen zu Themen vermitteln, die sie seit Jahren unreflektiert bearbeiten. Diese Website gibt Dir keine Anweisungen zu den zu verwendenden Tools, sondern bietet Vorschläge für verschiedene Optionen und erläutert nach Möglichkeit die Unterschiede in Ansatz und Anwendungsfall.

Dieses Dokument wird fortlaufend aktualisiert und mit hilfreichen Informationen und Beispielen ergänzt, sobald diese verfügbar sind.

Übersetzungen

Das Original, PHP the right way wurde in viele Sprachen übersetzt:

Diese Übersetzung ins Deutsche wurde von Henrik Pantle aka skipper-henrik besorgt.

Buch

Die neueste Version von PHP - aber richtig ist in der englischen Originalversion als PHP: The Right Way auch in den Formaten PDF, EPUB und MOBI verfügbar. Zu Leanpub

Wie Mithelfen?

Hilf mit, diese Website zur besten Ressource für neue PHP-Programmierer zu machen! Contribute on GitHub

Back to Top

Erste Schritte

Verwende die aktuelle stabile Version (8.4)

Wenn Du PHP neu ausprobieren möchtest, starte mit der aktuellen stabilen Version PHP 8.4. PHP 8.x bietet gegenüber den älteren Versionen 7.x und 5.x viele neue Funktionen. Die Engine wurde weitgehend neu entwickelt, und PHP ist jetzt noch schneller als ältere Versionen. PHP 8 ist ein umfassendes Update der Sprache und enthält viele neue Funktionen und Optimierungen.

Du solltest versuchen, schnellstmöglich auf die neueste stabile Version zu aktualisieren – PHP 7.4 ist bereits veraltet. Das Upgrade ist einfach, da es kaum Probleme mit der Abwärtskompatibilität gibt PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3, PHP 8.4. Wenn Du nicht sicher bist, in welcher Version eine Funktion oder ein Feature enthalten ist, kannst Du die PHP-Dokumentation auf der Website php.net einsehen.

Der mitgelieferte Web-Server

Mit PHP 5.4 oder neuer kannst Du PHP lernen, ohne einen kompletten, vollwertigen Webserver installieren und konfigurieren zu müssen. Um den Server zu starten, führe den folgenden Befehl im Terminal aus dem Root-Verzeichnis Deines Projekts aus:

> php -S localhost:8000

macOS Setup

macOS 12 (Monterey) und neuere Versionen enthalten kein vorinstalliertes PHP mehr. Frühere macOS-Versionen enthalten PHP, liegen aber hinter der neuesten stabilen Version zurück. Es gibt mehrere Möglichkeiten, die neueste PHP-Version unter macOS zu installieren.

Installiere PHP mit Homebrew

Homebrew ist ein Paketmanager für macOS, mit dem Du PHP und verschiedene Erweiterungen einfach installieren kannst. Das Homebrew-Core-Repository bietet „Formeln“ für PHP 8.1, 8.2, 8.3 und 8.4. Installiere die neueste Version mit diesem Befehl:

brew install php

Du kannst zwischen Homebrew-PHP-Versionen wechseln, indem Du Ihre PATH Variable änderst. Alternativ kannst Du brew-php-switcher, um PHP-Versionen automatisch zu wechseln.

Du kannst auch manuell zwischen PHP-Versionen wechseln, indem Du die Verknüpfung aufhebst und die gewünschte Version verknüpfst:

brew unlink php
brew link --overwrite php@8.2
brew unlink php
brew link --overwrite php@8.3

Installier PHP mit Macports

Das MacPorts-Projekt ist eine Open-Source-Community-Initiative zur Entwicklung eines benutzerfreundlichen Systems zum Kompilieren, Installieren und Aktualisieren von Open-Source-Software auf Befehlszeilen-, X11- oder Aqua-Basis auf dem macOS-Betriebssystem.

MacPorts unterstützt vorkompilierte Binärdateien, sodass Du nicht jede Abhängigkeit aus den Quell-Tarball-Dateien neu kompilieren musst. Dies rettet Dein Leben, wenn auf Deinem System kein Paket installiert ist.

An diesem Punkt kannst Du php54, php55, php56, php70, php71, php72, php73, php74, php80, php81, php82 oder php83 mit dem Befehl port install installieren, zum Beispiel:

sudo port install php74
sudo port install php83

Und Du kannst den select Befehl ausführen, um Dein aktives PHP zu wechseln:

sudo port select --set php php83

Installier PHP mit phpbrew

phpbrew ist ein Tool zur Installation und Verwaltung mehrerer PHP-Versionen. Dies ist besonders nützlich, wenn zwei verschiedene Anwendungen/Projekte unterschiedliche PHP-Versionen erfordern und Sie keine virtuellen Maschinen verwenden.

Installiere PHP mit Liip’s binary installer

Eine weitere beliebte Option ist php-osx.liip.ch, das einfache Installationsmethoden für die Versionen 5.3 bis 7.3 bietet. Die von Apple installierten PHP-Binärdateien werden dabei nicht überschrieben, sondern alles an einem separaten Ort (/usr/local/php5) installiert.

Aus Quell-Code compilieren

Eine weitere Möglichkeit, die installierte PHP-Version zu kontrollieren, besteht darin, sie selbst zu kompilieren. Stelle in diesem Fall sicher, dass Du entweder Xcode oder Apples Ersatz “Command Line Tools for XCode” installiert hast, der im Apple Developer Center heruntergeladen werden kann.

All-in-One Installation

Die oben aufgeführten Lösungen verarbeiten hauptsächlich PHP selbst und bieten keine Sachen wie Apache, Nginx oder einen SQL-Server. All-in-One-Lösungen wie MAMP und XAMPP installieren diese Softwarekomponenten für Dich und verknüpfen sie miteinander. Die einfache Einrichtung geht jedoch auf Kosten der Flexibilität.

Windows Setup

Du kannst die Binärdateien von windows.php.net/download herunterladen. Nach der PHP-Extraktion empfiehlt es sich, den PATH auf das Stammverzeichnis Ihres PHP-Ordners (wo sich php.exe befindet) zu setzen, damit Sie PHP von überall ausführen können.

Für Schulungen und die lokale Entwicklung Kannst Du den integrierten Webserver mit PHP 5.4+ nutzen, sodass Du Dich nicht um die Konfiguration kümmern musst. Wenn Du eine All-in-One-Lösung mit vollwertigem Webserver und MySQL wünschst, helfen Dir Tools wie XAMPP, EasyPHP, OpenServer und WAMP, eine Windows-Entwicklungsumgebung schnell zum Laufen zu bringen. Allerdings unterscheiden sich diese Tools etwas von der Produktionsumgebung. Achte daher auf Umgebungsunterschiede, wenn Du unter Windows arbeitest und unter Linux deployst.

Wenn Du Dein Produktionssystem unter Windows betreibst, bietet IIS7 die stabilste und leistungsstärkste Lösung. Mit phpmanager (einem GUI-Plugin für IIS7) kannst Du PHP einfach konfigurieren und verwalten. IIS7 verfügt über integriertes FastCGI und ist sofort einsatzbereit. Du musst lediglich PHP als Handler konfigurieren. Für Support und weitere Ressourcen gibt es einen eigenen Bereich für PHP auf iis.net.

Wenn Du Deine Anwendung in unterschiedlichen Umgebungen in Entwicklung und Produktion ausführst, kann es beim Live-Einsatz zu ungewöhnlichen Fehlern kommen. Wenn Du unter Windows entwickeln und unter Linux (oder einem anderen Betriebssystem als Windows) deployst, solltest Du den Einsatz einer virtuellen Maschine in Betracht ziehen.

Chris Tankersley hat einen sehr hilfreichen Blog-Beitrag darüber verfasst, welche Tools er für die PHP-Entwicklung unter Windows verwendet.

Linux Setup

Die meisten GNU/Linux-Distributionen enthalten PHP aus den offiziellen Repositorien, diese Pakete liegen jedoch meist etwas hinter der aktuellen stabilen Version zurück. Es gibt mehrere Möglichkeiten, neuere PHP-Versionen für solche Distributionen zu erhalten.

Ubuntu-basierte Distributionen

Für Ubuntu und Debian-basierte GNU/Linux-Distributionen werden die besten Alternativen für native Pakete beispielsweise von Ondřej Surý bereitgestellt und gepflegt. Dies geschieht über sein Personal Package Archive (PPA) für Ubuntu und DPA/bikeshed für Debian. Anweisungen dazu finden Sie unten.

Für Ubuntu-Distributionen bietet das PPA von Ondřej Surý unterstützte PHP-Versionen sowie zahlreiche PECL-Erweiterungen. Um dieses PPA zu Ihrem System hinzuzufügen, führen Sie die folgenden Schritte in Ihrem Terminal aus:

  1. Fügen Sie zunächst das PPA mit dem folgenden Befehl zu den Softwarequellen Ihres Systems hinzu:

    sudo add-apt-repository ppa:ondrej/php
    
  2. Aktualisieren Sie nach dem Hinzufügen des PPA die Paketliste Ihres Systems:

    sudo apt update
    

Dadurch wird sichergestellt, dass Ihr System auf die neuesten im PPA verfügbaren PHP-Pakete zugreifen und diese installieren kann.

Debian-basierte Distributionen

Für Debian-basierte Distributionen stellt Ondřej Surý auch einen bikeshed (Debian-Äquivalent eines PPA) zur Verfügung. Um den Bikeshed Deinem System hinzuzufügen und zu aktualisieren, gehe wie folgt vor:

  1. Stelle sicher, dass Sie Root-Zugriff haben. Andernfalls müssen Sie möglicherweise sudo für die folgenden Befehle verwenden.

  2. Aktualisiere die Paketliste Ihres Systems:

    sudo apt-get update
    
  3. Installiere lsb-release, ca-certificates, und curl:

    sudo apt-get -y install lsb-release ca-certificates curl
    
  4. Lade den Signaturschlüssel für das Repository herunter:

    sudo curl -sSLo /usr/share/keyrings/deb.sury.org-php.gpg https://packages.sury.org/php/apt.gpg
    
  5. Füge das Repository zu den Softwarequellen Deines Systems hinzu:

    sudo sh -c 'echo "deb [signed-by=/usr/share/keyrings/deb.sury.org-php.gpg] https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list'
    
  6. Aktualisiere abschließend die Paketliste Deines Systems erneut:

    sudo apt-get update
    

Mit diesen Schritten kann Ihr System die neuesten PHP-Pakete aus dem Bikeshed installieren.

RPM-basierte Distributionen

Auf RPM-basierten Distributionen (CentOS, Fedora, RHEL usw.) kannst Du Remi’s RPM repository verwenden , um die neueste PHP-Version zu installieren oder mehrere PHP-Versionen gleichzeitig verfügbar zu haben.

Zum Konfigurieren Ihrer RPM-basierten Distribution steht ein Konfigurationsassistent zur Verfügung.

Abgesehen davon kannst Du immer Container verwenden oder den PHP-Quellcode von Grund auf neu kompilieren.

Gemeinsame Datei- und Verzeichnisstruktur

Eine häufige Frage von Webentwicklern lautet: “Wo speichere ich meine Zeug?“ Über die Jahre lautete die Antwort immer wieder: „Dort wo das DocumentRoot ist.“ Obwohl diese Antwort nicht vollständig ist, bietet sie einen guten Ausgangspunkt.

Aus Sicherheitsgründen sollten Konfigurationsdateien für Besucher einer Website unzugänglich sein. Daher werden öffentliche Skripte in einem öffentlichen Verzeichnis und private Konfigurationen und Daten außerhalb dieses Verzeichnisses gespeichert.

Jedes Team, jedes CMS oder jedes Framework verwendet eine Standardverzeichnisstruktur. Wenn man jedoch ein Projekt alleine startet, kann die Wahl der richtigen Dateistruktur ganz schön herausfordernd sein.

Paul M. Jones hat die gängigen Vorgehensweisen von Zehntausenden von GitHub-Projekten im PHP-Bereich umfassend untersucht. Basierend auf dieser Forschung hat er eine standardisierte Datei- und Verzeichnisstruktur entwickelt: Das Standard PHP Package Skeleton. In dieser Verzeichnisstruktur sollte DocumentRoot auf public/ verweisen, Unit-Tests sollten im Verzeichnis tests/ abgelegt sein und Drittanbieterbibliotheken, wie sie von composer installiert wurden, gehören ins vendor/-Verzeichnis. Für andere Dateien und Verzeichnisse ist es für Projektbeteiligte am sinnvollsten, sich an das Standard PHP Package Skeleton zu halten.

Back to Top

Code Style Guide

Die PHP-Community ist groß und vielfältig und besteht aus unzähligen Bibliotheken, Frameworks und Komponenten. PHP-Entwickler wählen häufig mehrere davon aus und kombinieren sie in einem Projekt. Es ist wichtig, dass der PHP-Code (so nah wie möglich) einem gemeinsamen Codestil folgt, damit Entwickler verschiedene Bibliotheken für ihre Projekte problemlos kombinieren können.

Die Framework Interop Group hat eine Reihe von Stilempfehlungen vorgeschlagen und verabschiedet. Nicht alle beziehen sich auf den Codestil, aber PSR-1, PSR-12, PSR-4 and PER Coding Style machen es. Diese Empfehlungen stellen lediglich eine Reihe von Regeln dar, die von vielen Projekten wie Drupal, Zend, Symfony, Laravel, CakePHP, phpBB, AWS SDK, FuelPHP, Lithium usw. übernommen werden. Sie können diese Empfehlungen für Ihre eigenen Projekte verwenden oder Ihren persönlichen Stil beibehalten.

Idealerweise schreiben Sie PHP-Code, der einem bekannten Standard entspricht. Dies kann eine beliebige Kombination von PSRs oder einer der Codierungsstandards von PEAR oder Zend sein. So können andere Entwickler Ihren Code problemlos lesen und bearbeiten, und Anwendungen, die die Komponenten implementieren, gewährleisten Konsistenz auch bei der Verwendung von viel Drittanbieter-Code.

Du kannst PHP_CodeSniffer verwenden, um Code anhand einer dieser Empfehlungen zu überprüfen, und Plugins für Texteditoren wie Sublime Text, um Feedback in Echtzeit zu erhalten.

Du kannst das Code-Layout automatisch korrigieren, indem Du eines der folgenden Tools verwendest:

Es werden Fehler angezeigt und deren Behebung beschrieben. Es kann auch hilfreich sein, den phpcs Befehl in einen Git-Pre-Commit-Hook mit dem --filter=GitStaged CLI-Argument einzubinden. So kann Code, der gegen den gewählten Standard verstößt, erst dann in das Repository gelangen, wenn diese Verstöße behoben wurden.

Wenn Du über PHP_CodeSniffer verfügst, kannst Du die von ihm gemeldeten Code-Layoutprobleme automatisch mit dem PHP Code Beautifier and Fixer beheben.

phpcbf -w --standard=PSR1 file.php

Alternativ können Sie den PHP Coding Standards Fixer verwenden. Dieser zeigt Dir, welche Fehler die Codestruktur vor der Behebung aufwies.

php-cs-fixer fix -v --rules=@PSR1 file.php

Für alle Symbolnamen und die Code-Infrastruktur wird Englisch bevorzugt. Kommentare können in jeder Sprache verfasst werden, die für alle aktuellen und zukünftigen Beteiligten, die an der Codebasis arbeiten, leicht verständlich ist.

Eine gute ergänzende Ressource zum Schreiben von sauberem PHP-Code ist Clean Code PHP.

Back to Top

Sprachhighlights

Programmierparadigmen

PHP ist eine flexible, dynamische Sprache, die eine Vielzahl von Programmiertechniken unterstützt. Sie hat sich im Laufe der Jahre dramatisch weiterentwickelt, insbesondere durch die Einführung eines soliden objektorientierten Modells in PHP 5.0 (2004), anonymer Funktionen und Namespaces in PHP 5.3 (2009) und Traits in PHP 5.4 (2012).

Objektorientierte Programmierung

PHP verfügt über einen sehr umfassenden Satz objektorientierter Programmierfunktionen, darunter Unterstützung für Klassen, abstrakte Klassen, Schnittstellen, Vererbung, Konstruktoren, Klonen, Ausnahmen und mehr.

Funktionale Programmierung

PHP unterstützt First-Class-Funktionen, d. h., eine Funktion kann einer Variable zugewiesen werden. Sowohl benutzerdefinierte als auch integrierte Funktionen können von einer Variable referenziert und dynamisch aufgerufen werden. Funktionen können als Argumente an andere Funktionen übergeben werden (eine Feature namens Higher-order Functions) und Funktionen können andere Funktionen zurückgeben.

Rekursion, eine Feature, die es einer Funktion ermöglicht, sich selbst aufzurufen, wird von der Sprache unterstützt, der Großteil des PHP-Codes konzentriert sich jedoch auf Iteration.

Neue anonyme Funktionen (mit Unterstützung für Closures) sind seit PHP 5.3 (2009) vorhanden.

PHP 5.4 hat die Möglichkeit hinzugefügt, Closures an den Gültigkeitsbereich eines Objekts zu binden und hat außerdem die Unterstützung für aufrufbare Funktionen verbessert, sodass diese in fast allen Fällen austauschbar mit anonymen Funktionen verwendet werden können.

Metaprogrammierung

PHP unterstützt verschiedene Formen der Metaprogrammierung durch Mechanismen wie die Reflection API und Magic Methods. Es gibt viele Magic Methods wie __get(), __set(), __clone(), __toString(), __invoke(), usw., die es Entwicklern ermöglichen, sich in das Klassenverhalten einzuklinken. Ruby-Entwickler bemängeln oft, dass PHP method_missing fehle , aber es ist als __call() and __callStatic() verfügbar.

Namespaces (Namensräume){#namespaces_title}

Wie bereits erwähnt, gibt es in der PHP-Community viele Entwickler, die viel Code erstellen. Das bedeutet, dass der PHP-Code einer Bibliothek möglicherweise denselben Klassennamen wie eine andere verwendet. Wenn beide Bibliotheken im selben Namespace verwendet werden, kollidieren sie und verursachen Probleme.

Namespaces lösen dieses Problem. Wie im PHP-Referenzhandbuch beschrieben, lassen sich Namespaces mit Betriebssystemverzeichnissen vergleichen, welche für die Dateien einen Namensraum anlegen; zwei Dateien mit gleichem Namen können in unterschiedlichen Verzeichnissen koexistieren. Ebenso können zwei PHP-Klassen mit gleichem Namen in unterschiedlichen PHP-Namespaces koexistieren. So einfach ist das.

Es ist wichtig, dass Du Deinem Code einen Namespace zuweist, damit er von anderen Entwicklern so verwendet werden kann, dass keine Konflikte mit anderen Bibliotheken befürchtet werden müssen.

Eine empfohlene Möglichkeit zur Verwendung von Namespaces wird in PSR-4 beschrieben . Ziel ist die Bereitstellung einer Standardkonvention für Dateien, Klassen und Namespaces, um Plug-and-Play-Code zu ermöglichen.

Im Oktober 2014 hat die PHP-FIG den vorherigen Autoloading-Standard PSR-0 als veraltet markiert . Sowohl PSR-0 als auch PSR-4 sind weiterhin problemlos nutzbar. Letzterer erfordert PHP 5.3, daher implementieren viele reine PHP 5.2-Projekte PSR-0.

Wenn Sie einen Autoloader-Standard für eine neue Anwendung oder ein neues Paket verwenden möchten, sehen Sie sich PSR-4 an.

Standard-PHP-Library

Die Standard-PHP-Library (SPL) ist im Lieferumfang von PHP enthalten und bietet eine Sammlung von Klassen und Schnittstellen. Sie besteht hauptsächlich aus häufig benötigten Datenstrukturklassen (Stack, Queue, Heap usw.) und Iteratoren, die diese Datenstrukturen durchlaufen können, oder Ihren eigenen Klassen, die SPL-Schnittstellen implementieren.

Command Line Interface

PHP wurde zum Schreiben von Webanwendungen entwickelt, eignet sich aber auch zum Skripting von Befehlszeilenschnittstellenprogrammen / command line interface (CLI) programs. PHP-CLI-Programme können helfen, gängige Aufgaben wie Tests, Bereitstellung und Anwendungsadministration zu automatisieren.

PHP-CLI-Programme sind leistungsstark, da Du den Code Deiner App direkt verwenden kannst, ohne dafür eine Web-GUI erstellen und sichern zu müssen. Achte jedoch darauf, Deine PHP-CLI-Skripte niemals in Deinem public web root zu platzieren!

Versuchen Sie, PHP über Ihre Befehlszeile auszuführen:

> php -i

Die -i Option zeigt Deine PHP-Konfiguration an, genau wie die Funktion phpinfo().

Diese -a Option bietet eine interaktive Shell, ähnlich der IRB von Ruby oder der interaktiven Shell von Python. Darüber hinaus gibt es eine Reihe weiterer nützlicher command line options (Kommandozeilenoptionen) .

Schreiben wir ein einfaches “Hello, $name”-CLI-Programm. Erstelle zum Ausprobieren eine Datei mit dem Namen hello.php, wie unten dargestellt.

<?php
if ($argc !== 2) {
    echo "Usage: php hello.php <name>" . PHP_EOL;
    exit(1);
}
$name = $argv[1];
echo "Hello, $name" . PHP_EOL;

PHP richtet zwei spezielle Variablen basierend auf den Argumenten ein, mit denen Dein Skript ausgeführt wird. $argc ist eine Integer-Variable, die die Anzahl der Argumente enthält , und $argv ist eine Array-Variable, die den Wert jedes Arguments enthält. Das erste Argument ist immer der Name Deiner PHP-Skriptdatei, in diesem Fall hello.php.

Der exit() Ausdruck wird mit einer Zahl ungleich Null verwendet, um die Shell darüber zu informieren, dass der Befehl fehlgeschlagen ist. Häufig verwendete Exit-Codes finden Sie hier .

So führen Sie unser obiges Skript über die Befehlszeile aus:

> php hello.php
Usage: php hello.php <name>
> php hello.php world
Hello, world

Xdebug

Eines der nützlichsten Tools in der Softwareentwicklung ist ein geeigneter Debugger. Er ermöglicht es Dir, die Ausführung Deines Codes zu verfolgen und den Inhalt des Stacks zu überwachen. Xdebug, der PHP-Debugger, kann von verschiedenen IDEs genutzt werden, um Breakpoints und Stack-Inspektionen bereitzustellen. Außerdem erlaubt er Tools wie PHPUnit und KCacheGrind das Ausführen von Code-Coverage-Analysen und Code-Profiling.

Du findest Dich in einer Zwickmühle wieder, mit var_dump()/print_r() findest Du noch immer keine Lösung - vielleicht solltest Du jetzt den Debugger verwenden.

Die Installation von Xdebug kann schwierig sein, aber eine seiner wichtigsten Funktionen ist “Remote Debugging” – wenn Du Code lokal entwickelst und ihn dann in einer VM oder auf einem anderen Server testest, ist Remote Debugging die Funktion, die Du sofort aktivieren möchtest.

Normalerweise änderst Du Deinen Apache VHost oder Deine .htaccess-Datei mit diesen Werten:

php_value xdebug.remote_host 192.168.?.?
php_value xdebug.remote_port 9000

“Remote-Host” und “Remote-Port” entsprechen Deinem lokalen Computer und dem Port, auf dem Deine IDE hört. Anschließend musst Du Deine IDE nur noch in den Verbindungsmodus versetzen und die URL laden:

http://your-website.example.com/index.php?XDEBUG_SESSION_START=1

Deine IDE fängt jetzt den aktuellen Status ab, während das Skript ausgeführt wird, sodass Du Haltepunkte festlegen und die Werte im Speicher überprüfen kannst.

Grafische Debugger erleichtern das schrittweise Durchlaufen von Code, das Überprüfen von Variablen und die Auswertung von Code in der Live-Laufzeitumgebung. Viele IDEs bieten integrierte oder Plugin-basierte Unterstützung für grafisches Debugging mit Xdebug. MacGDBp ist eine kostenlose, Open-Source- und eigenständige Xdebug-GUI für macOS.

Back to Top

Dependency Management (Abhängigkeiten-Verwaltung)

Es gibt eine riesige Auswahl an PHP-Libraries, Frameworks und Komponenten. Ihr Projekt wird wahrscheinlich mehrere davon verwenden – dies sind Projektabhängigkeiten (Dependencies). PHP bot bisher keine gute Möglichkeit, diese Projektabhängigkeiten zu verwalten. Selbst bei manueller Verwaltung mussten Sie sich immer noch um Autoloader kümmern. Das ist kein Problem mehr.

Derzeit gibt es zwei wichtige Paketverwaltungssysteme für PHP: Composer und PEAR. Composer ist derzeit der beliebteste Paketmanager für PHP, PEAR war jedoch lange Zeit der am häufigsten verwendete Paketmanager. Es ist ratsam, die Geschichte von PEAR zu kennen, da Du möglicherweise auch dann noch Referenzen darauf findest, auch wenn Du es nie verwendest.

Composer und Packagist

Composer ist der empfohlene Abhängigkeitsmanager für PHP. Listen Sie die Abhängigkeiten Ihres Projekts in einer composer.json Datei auf. Mit wenigen einfachen Befehlen lädt Composer die Abhängigkeiten Deines Projekts herunter und richtet das autoloading für Dich ein. Composer entspricht NPM in der Node.js-Welt oder Bundler in der Ruby-Welt.

Es gibt eine Vielzahl von PHP-Bibliotheken, die mit Composer kompatibel sind und in Ihrem Projekt eingesetzt werden können. Diese “packages” finden Sie auf Packagist, dem offiziellen Repository für Composer-kompatible PHP-Bibliotheken.

So installierst Du Composer

Der sicherste Weg, Composer herunterzuladen, ist den offiziellen Anweisungen zu folgen. Dadurch wird sichergestellt, dass das Installationsprogramm nicht beschädigt oder manipuliert ist. Das Installationsprogramm installiert eine composer.phar Binärdatei in Deinem aktuellen Arbeitsverzeichnis.

Wir empfehlen, Composer global zu installieren (z. B. eine einzelne Kopie in /usr/local/bin). Führe dazu als Nächstes diesen Befehl aus:

mv composer.phar /usr/local/bin/composer

Hinweis: Wenn das oben genannte Verfahren aufgrund von Berechtigungen fehlschlägt, verwende das sudo Präfix

Um einen lokal installierten Composer auszuführen, verwende php composer.phar, global ist es einfach composer.

Installation unter Windows

Für Windows-Benutzer ist die einfachste Möglichkeit um los zu legen die Verwendung des ComposerSetup -Installationsprogramms, das eine globale Installation durchführt und Dein $PATH so einrichtet, dass Du einfach composer aus jedem Verzeichnis in Ihrer Befehlszeile aufrufen kannst.

So definieren und installieren Sie Abhängigkeiten

Composer speichert die Abhängigkeiten Ihres Projekts in einer Datei namens composer.json. Du kannst diese manuell verwalten oder Composer selbst verwenden. Der composer require Befehl fügt eine Projektabhängigkeit hinzu und falls Du keine composer.json Datei hast, wird eine erstellt. Hier ist ein Beispiel, das Twig als Dependency Deines Projekts hinzufügt.

composer require twig/twig:^2.0

Alternativ führt Sie der composer init Befehl durch die Erstellung einer vollständigen composer.json Datei für Dein Projekt. Sobald Du Deine composer.jsonDatei erstellt hast, kannst Du Composer anweisen, Deine Dependencies herunterzuladen und im vendor/ Verzeichnis zu installieren. Dies gilt auch für heruntergeladene Projekte, die bereits eine composer.json Datei bereitstellen:

composer install

Fügen Sie als Nächstes diese Zeile zur primären PHP-Datei Ihrer Anwendung hinzu. Dadurch wird PHP angewiesen, den Autoloader von Composer für Ihre Projektabhängigkeiten zu verwenden.

<?php
require 'vendor/autoload.php';

Jetzt können Sie Ihre Dependencies verwenden, diese werden bei Bedarf automatisch geladen.

Aktualisieren Ihrer Dependencies (Abhängigkeiten)

Composer erstellt eine Datei namens composer.lock, in der die genaue Version jedes heruntergeladenen Pakets gespeichert ist, als Du zum ersten Mal composer install ausgeführt hattest. Wenn Du Dein Projekt mit anderen teilst, stelle sicher, dass die composer.lock Datei enthalten ist, damit dein Kollege beim Ausführen von composer install die gleichen Versionen erhält wie Du. Um Ihre Abhängigkeiten zu aktualisieren, führe composer update aus. Verwende composer update nicht beim Deployen, sondern nur composer install. Sonst bekommst Du in der Produktion womöglich unterschiedliche Paketversionen.

Dies ist besonders nützlich, wenn Du Deine Versionsanforderungen flexibel definierst. Beispielsweise hat die Versionsanforderung von ~1.8 die Bedeutung “alles, was neuer als 1.8.0, aber kleiner als 2.0.x-dev ist”. Du kannst auch das Platzhalterzeichen * wie in 1.8.* verwenden . Der composer update Befehl aktualisiert nun alle Deine Abhängigkeiten auf die neueste Version, die den von Deinen definierten Einschränkungen entspricht.

Update-Benachrichtigungen

Um Benachrichtigungen über neue Versions-Veröffentlichungen zu erhalten, kannst Du Dich bei libraries.io anmelden, einem Webdienst, der Abhängigkeiten überwachen und Dir Benachrichtigungen zu Aktualisierungen senden kann.

Überprüfen Deiner Abhängigkeiten auf Sicherheitsprobleme

Der Local PHP Security Checker ist ein Befehlszeilentool, das Deine composer.lock Datei untersucht und Dir mitteilt, ob Du eine Deiner Abhängigkeiten aktualisieren musst.

The Local PHP Security Checker is a command-line tool, which will examine your composer.lock file and tell you if you need to update any of your dependencies.

Handling globaler Abhängigkeiten mit Composer

Composer kann auch globale Abhängigkeiten und deren Binärdateien verarbeiten. Die Bedienung ist unkompliziert: Du musst Deinem Befehl lediglich das Präfix global voranstellen. Wenn Du beispielsweise PHPUnit installieren und global verfügbar machen möchtest, führe den folgenden Befehl aus:

composer global require phpunit/phpunit

Dadurch wird ein ~/.composer Ordner erstellt, in dem Deine globalen Abhängigkeiten gespeichert sind. Um die Binärdateien der installierten Pakete überall verfügbar zu haben, füge den ~/.composer/vendor/bin Ordner anschließend Deiner $PATH Variable hinzu.

PEAR - PHP Extension and Application Repository

Ein altbewährter Paketmanager, der von einigen PHP-Entwicklern nach wie vor geschätzt wird, ist PEAR Er verhält sich ähnlich wie Composer, weist aber einige bemerkenswerte Unterschiede auf.

PEAR erfordert für jedes Paket eine spezifische Struktur. Das bedeutet, dass der Autor des Pakets es für die Verwendung mit PEAR vorbereiten muss. Der Gebrauch eines Projekts, das nicht für die Verwendung mit PEAR vorbereitet wurde, ist unmöglich.

PEAR installiert Pakete global, d. h. nach der Installation stehen sie allen Projekten auf dem Server zur Verfügung. Dies ist sinnvoll, wenn viele Projekte dasselbe Paket mit derselben Version verwenden, kann aber zu Problemen führen, wenn Versionskonflikte zwischen zwei Projekten auftreten.

So installierst Du PEAR

Du kannst PEAR installieren, indem Du den .phar Installer herunterlädst und ausführst. Die PEAR-Dokumentation enthält detaillierte Installationsanweisungen für jedes Betriebssystem.

Wenn Du Linux nutzt, kannst Du auch einen Blick in den Paketmanager Deiner Distribution werfen. Debian und Ubuntu verfügen beispielsweise über ein apt php-pear-Paket. (apt: Advanced Package Tool)

So installiert Du ein package

Wenn das Package in der PEAR packages list gelistet ist, kannst Du es installieren, indem Du den offiziellen Namen angibst:

pear install foo

Wenn das Paket auf einem anderen Kanal gehostet wird, musst Du zuerst den Kanal entdecken/discovern und ihn bei der Installation angeben. Weitere Informationen zu diesem Thema findest Du in der Dokumentation zur Kanalverwendung Using channel docs.

Handhabung von PEAR-Abhängigkeiten mit Composer

Wenn Sie Composer bereits verwenden und zusätzlich auch PEAR-Code installieren möchten, können Sie Composer zur Verwaltung Ihrer PEAR-Abhängigkeiten verwenden. PEAR-Repositorys werden von Composer Version 2 nicht mehr direkt unterstützt. Du Musst daher manuell ein Repository hinzufügen, um PEAR-Pakete zu installieren:

{
    "repositories": [
        {
            "type": "package",
            "package": {
                "name": "pear2/pear2-http-request",
                "version": "2.5.1",
                "dist": {
                    "url": "https://github.com/pear2/HTTP_Request/archive/refs/heads/master.zip",
                    "type": "zip"
                }
            }
        }
    ],
    "require": {
        "pear2/pear2-http-request": "*"
    },
    "autoload": {
        "psr-4": {"PEAR2\\HTTP\\": "vendor/pear2/pear2-http-request/src/HTTP/"}
    }
}

Der erste Abschnitt "repositories" teilt Composer mit, dass das Pear-Repository “initialisiert” (oder in der PEAR-Terminologie “discover”) werden soll. Anschließend stellt der require-Abschnitt dem Paketnamen ein Präfix voran:

pear-channel/package

Das “pear” Präfix ist fest codiert, um Konflikte zu vermeiden. Da ein Pear-Kanal beispielsweise mit dem vendor-Mamen eines anderen Pakets identisch sein könnte, kann der Kurzname des Kanals (oder die vollständige URL) verwendet werden, um anzugeben, in welchem ​​Kanal sich das Paket befindet.

Wenn dieser Code installiert ist, steht er in Deinem Vendor-Verzeichnis und automatisch über den Composer-Autoloader zur Verfügung:

vendor/pear2/pear2-http-request/pear2/HTTP/Request.php

Um dieses PEAR-Paket zu verwenden, verwise einfach folgendermaßen darauf:

<?php
require __DIR__ . '/vendor/autoload.php';

use PEAR2\HTTP\Request;

$request = new Request();

Back to Top

Coding Practices

Die Basics

PHP ist eine umfangreiche Sprache, die es Programmierern aller Erfahrungsstufen ermöglicht, nicht nur schnell, sondern auch effizient Code zu schreiben. Als Fortgeschrittene vergessen wir jedoch oft die Grundlagen, die wir anfangs gelernt haben (oder übersehen sie), und neigen zu Abkürzungen und/oder schlechten Angewohnheiten. Um diesem häufigen Problem entgegenzuwirken, soll dieser Abschnitt Programmierern die grundlegenden Programmierpraktiken in PHP in Erinnerung rufen.

Date and Time (Datum und Uhrzeit)

PHP verfügt über die Klasse DateTime, die Sie beim Lesen, Schreiben, Vergleichen oder Berechnen von Datum und Uhrzeit unterstützt. Neben DateTime bietet PHP viele weitere Funktionen für Datum und Uhrzeit. Für die meisten gängigen Anwendungen bietet DateTime eine praktische objektorientierte Schnittstelle. DateTime kann Zeitzonen verarbeiten, dies geht jedoch über den Rahmen dieser kurzen Einführung hinaus.

Um mit DateTime zu arbeiten, konvertiere das Rohdaten und -zeiten mit der createFromFormat() Factory-Methode in ein Objekt oder rufe mit new DateTime das aktuelle Datum und die aktuelle Uhrzeit ab. Verwende die format()-Methode, um DateTime für die Ausgabe wieder in einen String umzuwandeln.

<?php
$raw = '22. 11. 1968';
$start = DateTime::createFromFormat('d. m. Y', $raw);

echo 'Start date: ' . $start->format('Y-m-d') . PHP_EOL;

Berechnungen mit DateTime sind mit der Klasse DateInterval möglich. DateTime verfügt über Methoden wie add() und sub(), die ein DateInterval als Argument akzeptieren. Schreibe keinen Code, der jeden Tag die gleiche Anzahl von Sekunden erwartet. Sowohl Sommerzeit- als auch Zeitzonenänderungen würden diese Annahme widerlegen. Verwende stattdessen Datumsintervalle. Um die Datumsdifferenz zu berechnen, verwenden Sie die diff()-Methode. Sie gibt ein neues DateInterval zurück, das sehr einfach darzustellen ist.

<?php
// create a copy of $start and add one month and 6 days
$end = clone $start;
$end->add(new DateInterval('P1M6D'));

$diff = $end->diff($start);
echo 'Difference: ' . $diff->format('%m month, %d days (total: %a days)') . PHP_EOL;
// Difference: 1 month, 6 days (total: 37 days)

Sie können Standardvergleiche für DateTime-Objekte verwenden:

<?php
if ($start < $end) {
    echo "Start is before the end!" . PHP_EOL;}

Ein letztes Beispiel zur Veranschaulichung der DatePeriod-Klasse. Sie wird verwendet, um wiederkehrende Ereignisse zu durchlaufen. Sie kann zwei DateTime-Objekte (Start und End) sowie das Intervall annehmen, für das alle dazwischenliegenden Ereignisse zurückgegeben werden.

<?php
// output all thursdays between $start and $end
$periodInterval = DateInterval::createFromDateString('first thursday');
$periodIterator = new DatePeriod($start, $periodInterval, $end, DatePeriod::EXCLUDE_START_DATE);
foreach ($periodIterator as $date) {
    // output each date in the period
    echo $date->format('Y-m-d') . ' ';
}

Eine beliebte PHP-API-Erweiterung ist Carbon. Sie übernimmt alle Funktionen der DateTime-Klasse und erfordert daher nur minimale Codeänderungen. Zu den zusätzlichen Funktionen gehören Lokalisierungsunterstützung, weitere Möglichkeiten zum Addieren, Subtrahieren und Formatieren eines DateTime-Objekts sowie die Möglichkeit, Ihren Code durch die Simulation eines Datums und einer Uhrzeit Ihrer Wahl zu testen.

Design Patterns (Entwurfsmuster)

Beim Erstellen Deine Anwendung ist es hilfreich, allgemeine Muster im Code und für die Gesamtstruktur Deines Projekts zu verwenden. Die Verwendung allgemeiner Muster erleichtert die Verwaltung Deines Codes erheblich und ermöglicht anderen Entwicklern ein schnelles Verständnis wie in Deinem Code alles miteinander zusammenhängt.

Wenn Du ein Framework verwendest, basiert der Großteil des übergeordneten Codes und der Projektstruktur auf diesem Framework. Daher werden dann viele Musterentscheidungen für Dich getroffen. Du musst jedoch weiterhin die besten Muster für Deinen Code auswählen, wenn dieser auf dem Framework basiert. Wenn Du hingegen kein Framework zur Erstellung Deiner Anwendung verwendest, musst Du Muster finden, die am besten zu Art und Größe Deiner Anwendung passen.

Weitere Informationen zu PHP-Entwurfsmustern und funktionierende Beispiele findest Du unter:

Arbeiten mit UTF-8

Dieser Abschnitt wurde ursprünglich von Alex Cabal für PHP Best Practices geschrieben und diente als Grundlage für unsere eigenen UTF-8-Empfehlungen.

Es gibt keinen Einzeiler. Seien Sie sorgfältig, detailliert und konsistent.

PHP unterstützt Unicode derzeit nicht auf niedriger Ebene. Es gibt Möglichkeiten, die korrekte Verarbeitung von UTF-8-Strings sicherzustellen, aber das ist nicht einfach und erfordert die Auseinandersetzung mit fast allen Ebenen der Webanwendung, von HTML über SQL bis hin zu PHP. Wir geben hier eine kurze, praktische Zusammenfassung.

UTF-8 auf PHP-Ebene

Die grundlegenden String-Operationen, wie das Verketten zweier Strings und das Zuweisen von Strings zu Variablen, erfordern für UTF-8 keine besonderen Anforderungen. Die meisten String-Funktionen, wie strpos() und strlen(), erfordern jedoch besondere Aufmerksamkeit. Diese Funktionen haben oft ein mb_* Gegenstück, beispielsweise mb_strpos() and mb_strlen(). Diesemb_*-Strings werden Dir über die Multibyte String Extension zur Verfügung gestellt und sind speziell für die Verarbeitung von Unicode-Strings konzipiert.

Du musst die mb_*-Funktionen immer dann verwenden, wenn Du mit einer Unicode-Zeichenfolge arbeitest. Wenn Du substr() auf eine UTF-8-Zeichenfolge anwendet, besteht eine grosse Möglichkeit, dass das Ergebnis einige unleserliche Halbzeichen enthält. Die korrekte Funktion wäre das Multibyte-Gegenstück mb_substr().

Das Schwierige ist, immer daran zu denken, die mb_*-Funktionen zu verwenden. Wenn Du es auch nur einmal vergisst, besteht die Gefahr, dass Deine Unicode-Zeichenfolge bei der weiteren Verarbeitung verstümmelt wird.

Nicht alle String-Funktionen haben ein mb_*-Gegenstück. Wenn es für Ihre Aufgabe keins gibt, haben Sie möglicherweise Pech gehabt.

Du solltest diemb_internal_encoding()-Funktion am Anfang jedes PHP-Skripts (oder am Anfang Ihres globalen Include-Skripts) verwenden und die mb_http_output()-Funktion direkt dahinter, wenn Dein Skript an einen Browser ausgegeben wird. Die explizite Definition der Zeichenkettenkodierung in jedem Skript erspart Dir später viel Ärger.

Darüber hinaus verfügen viele PHP-Funktionen, die mit Zeichenfolgen arbeiten, über einen optionalen Parameter, mit dem Sie die Zeichenkodierung festlegen können. Geben Sie bei dieser Option immer explizit UTF-8 an. Beispielsweise bietet htmlentities() eine Option für die Zeichenkodierung, und Du solltest bei der Verarbeitung solcher Zeichenfolgen immer UTF-8 angeben. Beachte, dass ab PHP 5.4.0 UTF-8 die Standardkodierung für htmlentities() und htmlspecialchars()ist.

Abschießend, wenn Du eine verteilte Anwendung erstellst und nicht sicher bist, ob die mbstring-Erweiterung verwendbar ist, solltest Du das Composer-Paket symfony/polyfill-mbstring verwenden. Dieses wird mbstring bei Verfügbarkeit verwenden und greift andernfalls auf Nicht-UTF-8-Funktionen zurück.

UTF-8 auf Datenbankebene

Wenn Dein PHP-Skript auf MySQL zugreift, besteht die Möglichkeit, dass Deine Strings als Nicht-UTF-8-Strings in der Datenbank gespeichert werden, selbst wenn Sie alle oben genannten Vorsichtsmaßnahmen befolgen.

Um sicherzustellen, dass Dein Strings von PHP in UTF-8 an MySQL übertragen werden, stelle sicher, dass Ihre Datenbank und Tabellen auf den utf8mb4 entsprechenden Zeichensatz und die entsprechende Sortierung eingestellt sind und dass Sie den utf8mb4 Zeichensatz im PDO-Connection-String verwendest. Siehe untensthender Beispielcode. Das ist äußerst wichtig.

Beachte, dass Du für die vollständige UTF-8-Unterstützung den utf8mb4-Zeichensatz verwenden musst, nicht den utf8-Zeichensatz! Weitere Informationen findest Du im Abschnitt „Weitere Informationen“.

UTF-8 auf Browserebene

Verwende die mb_http_output()-Funktion, um sicherzustellen, dass Dein PHP-Skript wirklich UTF-8-Zeichenfolgen an Deinen Browser ausgibt.

Der Browser muss dann durch die HTTP-Response informiert werden, dass diese Seite als UTF-8 betrachtet werden soll. Heutzutage ist es üblich, den Zeichensatz im HTTP-Response-Header wie folgt festzulegen:

<?php
header('Content-Type: text/html; charset=UTF-8')

Der bisherige Ansatz hierfür bestand darin, das charset <meta>-Tag in das <head>-Tag Ihrer Seite aufzunehmen.

<?php
// Tell PHP that we're using UTF-8 strings until the end of the script
mb_internal_encoding('UTF-8');
$utf_set = ini_set('default_charset', 'utf-8');
if (!$utf_set) {
    throw new Exception('could not set default_charset to utf-8, please ensure it\'s set on your system!');
}

// Tell PHP that we'll be outputting UTF-8 to the browser
mb_http_output('UTF-8');
 
// Our UTF-8 test string
$string = 'Êl síla erin lû e-govaned vîn.';

// Transform the string in some way with a multibyte function
// Note how we cut the string at a non-Ascii character for demonstration purposes
$string = mb_substr($string, 0, 15);

// Connect to a database to store the transformed string
// See the PDO example in this document for more information
// Note the `charset=utf8mb4` in the Data Source Name (DSN)
$link = new PDO(
    'mysql:host=your-hostname;dbname=your-db;charset=utf8mb4',
    'your-username',
    'your-password',
    array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_PERSISTENT => false
    )
);

// Store our transformed string as UTF-8 in our database
// Your DB and tables are in the utf8mb4 character set and collation, right?
$handle = $link->prepare('insert into ElvishSentences (Id, Body, Priority) values (default, :body, :priority)');
$handle->bindParam(':body', $string, PDO::PARAM_STR);
$priority = 45;
$handle->bindParam(':priority', $priority, PDO::PARAM_INT); // explicitly tell pdo to expect an int
$handle->execute();

// Retrieve the string we just stored to prove it was stored correctly
$handle = $link->prepare('select * from ElvishSentences where Id = :id');
$id = 7;
$handle->bindParam(':id', $id, PDO::PARAM_INT);
$handle->execute();

// Store the result into an object that we'll output later in our HTML
// This object won't kill your memory because it fetches the data Just-In-Time to
$result = $handle->fetchAll(\PDO::FETCH_OBJ);

// An example wrapper to allow you to escape data to html
function escape_to_html($dirty){
    echo htmlspecialchars($dirty, ENT_QUOTES, 'UTF-8');
}

header('Content-Type: text/html; charset=UTF-8'); // Unnecessary if your default_charset is set to utf-8 already
?><!doctype html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>UTF-8 test page</title>
    </head>
    <body>
        <?php
        foreach($result as $row){
            escape_to_html($row->Body);  // This should correctly output our transformed UTF-8 string to the browser
        }
        ?>
    </body>
</html>

Weiterführende Literatur

Internationalisierung (i18n) und Lokalisierung (l10n)

Disclaimer für Neulinge: i18n und l10n sind Numeronyme, eine Art Abkürzung, bei der Zahlen zum Verkürzen von Wörtern verwendet werden – in unserem Fall wird Internationalisierung zu i18n und Lokalisierung zu l10n.

Zunächst müssen wir diese beiden ähnlichen Konzepte und andere damit zusammenhängende Dinge definieren:

Gängige Implementierungsmethoden

Der einfachste Weg, PHP-Software zu internationalisieren, ist die Verwendung von Array-Dateien und deren Strings in Vorlagen wie z.B. <h1><?=$TRANS['title_about_page']?></h1>. Dieser Weg ist jedoch für ernsthafte Projekte kaum zu empfehlen, da er im Laufe der Zeit einige Wartungsprobleme mit sich bringt – einige davon können bereits zu Beginn auftreten, wie z. B. die Pluralisierung. Versuchen Sie diesen Weg daher bitte nicht, wenn Ihr Projekt mehr als ein paar Seiten umfasst.

Der klassischste Weg und oft als Referenz für i18n und l10n verwendet, ist ein Unix-Tool namens gettext. Es stammt aus dem Jahr 1995 und ist noch immer eine vollständige Implementierung für die Übersetzung von Software. Es ist einfach zu bedienen und bietet leistungsstarke Tools. Wir werden hier Gettext besprechen. Damit Sie sich nicht mit der Kommandozeile herumschlagen müssen, stellen wir Ihnen eine praktische GUI-Anwendung vor, mit der Sie Ihren l10n-Quellcode einfach aktualisieren können.

Andere Werkzeuge

Es gibt gängige Bibliotheken, die Gettext und andere i18n-Implementierungen unterstützen. Einige davon sind möglicherweise einfacher zu installieren oder bieten zusätzliche Funktionen oder i18n-Dateiformate. In diesem Dokument konzentrieren wir uns auf die Tools, die im PHP-Kern enthalten sind. Zur Vervollständigung listen wir hier weitere auf:

Andere Frameworks enthalten auch i18n-Module, diese sind jedoch außerhalb ihrer Codebasen nicht verfügbar:

Wenn Du Dich für eine der Bibliotheken entscheidest, die keine Extractors bereitstellen, möchtst Du möglicherweise die Gettext-Formate verwenden, sodass Du die ursprüngliche Gettext-Toolchain (einschließlich Poedit) verwenden kannst, wie im Rest des Kapitels beschrieben.

Gettext

Installation

Möglicherweise musst Du Gettext und die zugehörige PHP-Bibliothek mithilfe Deines Paketmanagers (z. B. apt-get or yum ) installieren. Aktiviere die Funktion nach der Installation, indem Du extension=gettext.so (Linux/Unix) oder extension=php_gettext.dll (Windows) zu Deiner php.ini hinzufügst.

Auch hier verwenden wir Poedit zum Erstellen von Übersetzungsdateien. Du wirst es wahrscheinlich im Paketmanager Deines Systems finden; es ist für Unix, macOS und Windows verfügbar und kann auch kostenlos auf deren Website heruntergeladen werden.

Struktur

Drei verschiedene Dateien

Bei der Arbeit mit gettext arbeitest Du üblicherweise mit drei Dateien. Die wichtigsten sind PO- (Portable Object) und MO- (Machine Object) Dateien. Erstere ist eine Liste lesbarer “übersetzter Objekte” und letztere die entsprechende Binärdatei, die gettext bei der Lokalisierung interpretiert. Es gibt außerdem eine POT-Datei (Template), die alle vorhandenen Schlüssel aus Deinen Quelldateien enthält und als Leitfaden zum Generieren und Aktualisieren aller PO-Dateien dient. Diese Template-Dateien sind nicht zwingend erforderlich: Je nach verwendetem l10n-Tool reichen PO/MO-Dateien aus. Du benötigst immer ein Paar PO/MO-Dateien pro Sprache und Region, aber nur eine POT-Datei pro Domänen.

Domänen

In großen Projekten kann es vorkommen, dass Übersetzungen getrennt werden müssen, wenn dieselben Wörter in einem bestimmten Kontext unterschiedliche Bedeutungen haben. In diesen Fällen werden sie in verschiedene Domänen aufgeteilt. Dabei handelt es sich im Wesentlichen um benannte Gruppen von POT-/PO-/MO-Dateien, wobei der Dateiname die jeweilige Übersetzungsdomäne ist. Kleine und mittelgroße Projekte verwenden der Einfachheit halber meist nur eine Domäne; ihr Name ist beliebig, wir verwenden für unsere Codebeispiele jedoch “main”. In Symfony-Projekten werden Domänen beispielsweise verwendet, um die Übersetzungen für Validierungsmeldungen zu trennen.

Gebietsschemacode

Ein Gebietsschema ist einfach ein Code, der eine Version einer Sprache identifiziert. Es wird gemäß den Spezifikationen ISO 639-1 und ISO 3166-1 alpha-2 definiert: Zwei Kleinbuchstaben für die Sprache, optional gefolgt von einem Unterstrich und zwei Großbuchstaben, die den Länder- oder Regionalcode kennzeichnen. Für seltene Sprachen werden drei Buchstaben verwendet.

Für manche Sprechende mag der Länderteil überflüssig erscheinen. Tatsächlich haben einige Sprachen in verschiedenen Ländern Dialekte, wie zum Beispiel Österreichisches Deutsch (de_AT) oder brasilianisches Portugiesisch (pt_BR). Der zweite Teil dient der Unterscheidung zwischen diesen Dialekten – fehlt er, wird er als “generische” oder “hybride” Version der Sprache angesehen.

Verzeichnisstruktur

Um Gettext verwenden zu können, benötigen wir eine bestimmte Ordnerstruktur. Wähle zunächst ein beliebiges Stammverzeichnis für Deine l10n-Dateien in Deinem Quell-Repository. Darin findest Du einen Ordner für jedes benötigte Gebietsschema und einen festen LC_MESSAGES Ordner für alle PO/MO-Paare. Beispiel:

<project root>
 ├─ src/
 ├─ templates/
 └─ locales/
    ├─ forum.pot
    ├─ site.pot
    ├─ de/
    │  └─ LC_MESSAGES/
    │     ├─ forum.mo
    │     ├─ forum.po
    │     ├─ site.mo
    │     └─ site.po
    ├─ es_ES/
    │  └─ LC_MESSAGES/
    │     └─ ...
    ├─ fr/
    │  └─ ...
    ├─ pt_BR/
    │  └─ ...
    └─ pt_PT/
       └─ ...

Pluralformen

Wie bereits in der Einleitung erwähnt, können verschiedene Sprachen unterschiedliche Pluralregeln haben. Gettext erspart uns jedoch auch dieses Problem. Beim Erstellen einer neuen .po-Datei musst Du die Pluralregeln für die jeweilige Sprache angeben, und übersetzte Teile, die pluralsensitiv sind haben für jede dieser Regeln eine andere Form. Beim Aufruf von Gettext im Code musst Du die Nummer des Satzes angeben, und Gettext ermittelt die korrekte Form – bei Bedarf sogar mithilfe von String-Ersetzungen.

Pluralregeln enthalten die Anzahl der verfügbaren Pluralformen und einen Boole’schen Test auf n, der definiert, in welche Regel die angegebene Zahl fällt (beginnend mit 0). Beispiel:

Nachdem Du nun die Grundlagen der Pluralregeln verstanden hast (und falls nicht, sieh Dir bitte eine ausführlichere Erklärung im LingoHub-Tutorial an), möchtst Du vielleicht die benötigten Regeln aus einer Liste kopieren, anstatt sie von Hand zu schreiben.

Wenn Du Gettext aufrufst, um Sätze mit Zählern zu lokalisieren, musst Du auch die zugehörige Nummer angeben. Gettext ermittelt die anzuwendende Regel und verwendet die korrekte lokalisierte Version. Für jede definierte Pluralregel musst Du einen anderen Satz in die .po-Datei aufnehmen.

Beispielimplementierung

Nach all der Theorie kommen wir nun zur Praxis. Hier ist ein Ausschnitt einer .po-Datei – achte nicht auf das Format, sondern auf den Gesamtinhalt. Wie Du ihn einfach bearbeiten kannst, erfährst Du später:

msgid ""
msgstr ""
"Language: pt_BR\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"

msgid "We are now translating some strings"
msgstr "Nós estamos traduzindo algumas strings agora"

msgid "Hello %1$s! Your last visit was on %2$s"
msgstr "Olá %1$s! Sua última visita foi em %2$s"

msgid "Only one unread message"
msgid_plural "%d unread messages"
msgstr[0] "Só uma mensagem não lida"
msgstr[1] "%d mensagens não lidas"

Der erste Abschnitt funktioniert wie eine Kopfzeile, wobei insbesondere msgid und msgstr leer sind. Er beschreibt die Dateikodierung, Pluralformen und andere weniger relevante Dinge. Der zweite Abschnitt übersetzt eine einfache Zeichenfolge vom Englischen in brasilianisches Portugiesisch und der dritte macht dasselbe, nutzt jedoch die Zeichenfolgenersetzung aus sprintf, sodass die Übersetzung den Benutzernamen und das Besuchsdatum enthalten kann. Der letzte Abschnitt ist ein Beispiel für Pluralformen, wobei die Singular- und Pluralversion im Englischen als msgid und die entsprechenden Übersetzungen als msgstr 0 und 1 angezeigt werden (entsprechend der durch die Pluralregel vorgegebenen Zahl). Auch hier wird die Zeichenfolgenersetzung verwendet, sodass die Zahl mithilfe %d direkt im Satz angezeigt wird. Die Pluralformen bestehen immer aus zwei msgid (Singular und Plural). Es wird daher empfohlen, keine komplexe Sprache als Übersetzungsquelle zu verwenden.

Discussion on l10n keys

Wie Du vielleicht bemerkt hast, verwenden wir als Quell-ID den englischen Originalsatz. Diese msgid wird in allen Deinen.po-Dateien verwendet. Das bedeutet, dass andere Sprachen dasselbe Format und dieselben msgid-Felder, aber übersetzte msgstr-Zeilen haben.

Wenn wir über Übersetzungsschlüssel sprechen, gibt es zwei verschiedene “Schulen”:

msgidals echter Satz . Auch wenn Teile der Software in einer bestimmten Sprache nicht übersetzt sind, behält der angezeigte Schlüssel eine gewisse Bedeutung. Beispiel: Wenn Du selbtst vom Englischen ins Spanische übersetzst, aber Hilfe beim Übersetzen ins Französische brauchst, veröffentlichst Du die neue Seite eben mit fehlenden französischen Sätzen, und Teile der Website werden stattdessen auf Englisch angezeigt. es ist für den Übersetzer viel einfacher zu verstehen, was vor sich geht, und auf der Grundlage des eine richtige Übersetzung anzufertigen msgid;

Sie erhalten „kostenloses“ L10n für eine Sprache – die Quellsprache. Der einzige Nachteil: Wenn Sie den eigentlichen Text ändern möchten, müssen Sie ihn msgidin mehreren Sprachdateien ersetzen.

  1. msgid als echter Satz. Die Hauptvorteile sind:
    • Auch wenn Teile der Software in einer bestimmten Sprache nicht übersetzt sind, behält der angezeigte Schlüssel immer noch eine gewisse Bedeutung. Beispiel: Wenn Du selbtst vom Englischen ins Spanische übersetzst, aber Hilfe beim Übersetzen ins Französische brauchst, veröffentlichst Du die neue Seite eben mit fehlenden französischen Sätzen, diese Teile der Website werden stattdessen in Englisch angezeigt;
    • es ist für den Übersetzer viel einfacher zu verstehen, was vor sich geht, und auf der Grundlage der msgid eine richtige Übersetzung anzufertigen;
    • Du erhältst “gratis”-l10n for one language - für eine Sprache – die Quellsprache;
    • Der einzige Nachteil: Wenn Du den eigentlichen Text ändern möchtest, musst Du die msgid in mehreren Sprachdateien ersetzen.
  2. msgid als eindeutiger, strukturierter Schlüssel. Er beschreibt strukturiert die Rolle des Satzes in der Anwendung und enthält das Template oder den Teil, in dem sich der String anstelle Deines Inhalts befindet.
    • Dies ist eine großartige Möglichkeit, den Code zu organisieren und den Textinhalt von der Templatelogik zu trennen.
    • Dies könnte jedoch zu Problemen für den Übersetzer führen, da der Kontext übersehen wird. Für weitere Übersetzungen wird eine Quellsprachendatei wird als Grundlage benötigt. Beispiel: Der Entwickler verfügt idealerweise über eine en.po-Datei, welche die Übersetzer lesen können, um zu verstehen, was sie in die fr.po-Datei schreiben sollen.
    • Fehlende Übersetzungen würden bedeutungslose IDs auf dem Bildschirm anzeigen (top_menu.welcome anstatt Hello there, User! auf der o.g. unübersetzten französischen Page). Das ist gut dafür, dass die Übersetzung vor der Veröffentlichung abgeschlossen sein muss – schlecht ist es jedoch, da Übersetzungsprobleme das Nutzererlebnis erheblich beeinträchtigen würden Einige Libraries bieten jedoch die Möglichkeit, eine bestimmte Sprache als “Fallback” festzulegen, was ein ähnliches Verhalten wie der obige Ansatz hat.

Das Gettext-Handbuch bevorzugt den ersten Ansatz, da dieser im Allgemeinen für Übersetzer und Benutzer im Problemfall einfacher ist. So werden wir auch hier vorgehen. Die Symfony-Dokumentation bevorzugt jedoch die schlüsselwortbasierte Übersetzung, um unabhängige Änderungen aller Übersetzungen zu ermöglichen, ohne dass auch die Templates davon betroffen sind.

Alltagsgebrauch

In einer typischen Anwendung verwendest Du Gettext-Funktionen beim Schreiben statischer Texte auf Deinen Seiten. Diese Sätze erscheinen dann in .po-Dateien, werden übersetzt, in .mo-Dateien kompiliert und anschließend von Gettext beim Rendern der eigentlichen Benutzeroberfläche verwendet. Lassen Sie uns daher die bisherigen Ausführungen in einem Schritt-für-Schritt-Beispiel zusammenfassen:

1. Eine Beispiel-Template, einschließlich einiger Gettext-Aufrufe

<?php include 'i18n_setup.php' ?>
<div id="header">
    <h1><?=sprintf(gettext('Welcome, %s!'), $name)?></h1>
    <!-- code indented this way only for legibility -->
    <?php if ($unread): ?>
        <h2><?=sprintf(
            ngettext('Only one unread message',
                     '%d unread messages',
                     $unread),
            $unread)?>
        </h2>
    <?php endif ?>
</div>

<h1><?=gettext('Introduction')?></h1>
<p><?=gettext('We\'re now translating some strings')?></p>

gettext()übersetzt einfach ein msgid in das entsprechende Element msgstr für eine bestimmte Sprache. Es gibt auch eine Kurzfunktion _(), die auf die gleiche Weise funktioniert. ngettext() macht dasselbe, aber mit Pluralregeln; Es gibt auch dgettext()und dngettext(), mit denen Du die Domäne für einen einzelnen Anruf überschreiben kannst. Mehr zur Domänenkonfiguration im nächsten Beispiel.

2. Eine Setup-Datei (i18n_setup.php wie oben), wählt das richtige Gebietsschemas und Konfiguration von Gettext aus.

<?php
/**
 * Verifies if the given $locale is supported in the project
 * @param string $locale
 * @return bool
 */
function valid($locale) {
   return in_array($locale, ['en_US', 'en', 'pt_BR', 'pt', 'es_ES', 'es']);
}

//setting the source/default locale, for informational purposes
$lang = 'en_US';

if (isset($_GET['lang']) && valid($_GET['lang'])) {
    // the locale can be changed through the query-string
    $lang = $_GET['lang'];    //you should sanitize this!
    setcookie('lang', $lang); //it's stored in a cookie so it can be reused
} elseif (isset($_COOKIE['lang']) && valid($_COOKIE['lang'])) {
    // if the cookie is present instead, let's just keep it
    $lang = $_COOKIE['lang']; //you should sanitize this!
} elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
    // default: look for the languages the browser says the user accepts
    $langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
    array_walk($langs, function (&$lang) { $lang = strtr(strtok($lang, ';'), ['-' => '_']); });
    foreach ($langs as $browser_lang) {
        if (valid($browser_lang)) {
            $lang = $browser_lang;
            break;
        }
    }
}

// here we define the global system locale given the found language
putenv("LANG=$lang");

// this might be useful for date functions (LC_TIME) or money formatting (LC_MONETARY), for instance
setlocale(LC_ALL, $lang);

// this will make Gettext look for ../locales/<lang>/LC_MESSAGES/main.mo
bindtextdomain('main', '../locales');

// indicates in what encoding the file should be read
bind_textdomain_codeset('main', 'UTF-8');

// if your application has additional domains, as cited before, you should bind them here as well
bindtextdomain('forum', '../locales');
bind_textdomain_codeset('forum', 'UTF-8');

// here we indicate the default domain the gettext() calls will respond to
textdomain('main');

// this would look for the string in forum.mo instead of main.mo
// echo dgettext('forum', 'Welcome back!');
?>

3. Übersetzung für den ersten Durchgang vorbereiten

Einer der großen Vorteile von Gettext gegenüber benutzerdefinierten Framework-i18n-Paketen ist sein umfangreiches und leistungsstarkes Dateiformat. “Oh Mann, das ist ziemlich schwer zu verstehen und manuell zu bearbeiten - ein simples Array wäre echt leichter!” Mach’ Dir keine Sorgen: Anwendungen wie Poedit helfen Dir dabei – und zwar sehr. Du kannst das Programm von der Website herunterladen; es ist kostenlos und für alle Plattformen verfügbar. Es ist ein recht einfach zu bedienendes und gleichzeitig sehr leistungsstarkes Tool, das alle Funktionen von Gettext nutzt. Diese Anleitung basiert auf PoEdit 1.8.

Wählen Sie im ersten Durchgang “File > New…” aus dem Menü. Du wirst direkt nach der Sprache gefragt: Hier kannst Du die gewünschte Sprache auswählen/filtern oder das oben erwähnte Format wie en_US oder pt_BR nutzen.

Speichere die Datei nun – in der ebenfalls beschriebenen Verzeichnisstruktur. Klicke anschließend auf “Extract from sources” und konfiguriere hier verschiedene Einstellungen für die Extraktions- und Übersetzungsaufgaben. Diese findest Du später unter “Catalog > Properties”:

Nachdem Sie diese Punkte festgelegt haben, durchsucht PoEdit Ihre Quelldateien nach allen Lokalisierungsaufrufen. Nach jedem Scan zeigt PoEdit eine Zusammenfassung der gefundenen und entfernten Einträge an. Neue Einträge werden in die Übersetzungstabelle eingefügt, und Du fängst mit der Eingabe der lokalisierten Versionen der Strings an. Speichere die Datei, und eine .mo-Datei wird im selben Ordner (neu) kompiliert. Und schon ist Dein Projekt internationalisiert.

4. Übersetzen von Strings

Wie Du vielleicht schon bemerkt hast, gibt es zwei Haupttypen lokalisierter Zeichenfolgen: Einfache und solche mit Pluralformen. Erstere bestehen lediglich aus zwei Feldern: Quelle und lokalisierter String. Der Quellstring kann nicht geändert werden, da Gettext/Poedit keine Möglichkeit zur Änderung Deiner Quelldateien bietet. Du musst die Quelle selbst ändern und die Dateien erneut scannen. Tipp: Klicke mit der rechten Maustaste auf eine Übersetzungszeile, um Hinweise zu den Quelldateien und Zeilen zu erhalten, in denen dieser String verwendet wird. Zeichenfolgen mit Pluralformen hingegen enthalten zwei Felder zur Anzeige der beiden Quellzeichenfolgen und Registerkarten zur Konfiguration der verschiedenen Endformen.

Wenn Du Deine Quellen ändern und die Übersetzungen aktualisieren musst, klicke einfach auf “Aktualisieren”. Poedit scannt den Code erneut, entfernt nicht vorhandene Einträge, verbindet geänderte und fügt neue hinzu. Es kann auch versuchen, einige Übersetzungen aufgrund Deiner anderen Übersetzungen zu erraten. Diese Versuche und die geänderten Einträge werden mit einem “Fuzzy”-Marker markiert, der auf eine Überprüfung hinweist und in der Liste goldgelb angezeigt wird. Dies ist auch nützlich, wenn Du ein Übersetzungsteam hast und jemand versucht, etwas zu schreiben, bei dem er sich nicht sicher ist: Markiereie einfach “Fuzzy”, und jemand anderes überprüft später.

Abschliessend empfehlen wir , “Ansicht > Nicht übersetzte Einträge zuerst” aktiviert zu lassen, da dies sehr hilft, keine Einträge zu vergessen. Von diesem Menü aus kannst Du auch Teile der Benutzeroberfläche öffnen, in denen Du bei Bedarf Kontextinformationen für Übersetzer hinterlassen knnst.

Tipps & Tricks

Mögliche Caching-Probleme

Wenn Du PHP als Modul auf Apache (mod_php) ausführst, können Probleme mit dem caching der .mo-Datei auftreten. Dies geschieht beim ersten Lesen. Um die Datei zu aktualisieren, ist möglicherweise ein Serverneustart erforderlich. Unter Nginx und PHP5 genügen in der Regel ein paar Seitenaktualisierungen, um den Übersetzungscache zu aktualisieren. Unter PHP7 ist dies selten erforderlich.

Zusätzliche Hilfsfunktionen

Viele bevorzugen, da es einfacher zu verwenden ist, _() anstatt gettext(). Viele benutzerdefinierte i18n-Bibliotheken von Frameworks verwenden ebenfalls etwas Ähnliches wie t(), um übersetzten Code zu verkürzen. Dies ist jedoch die einzige Funktion mit einer Verknüpfung. Du kannst Deinem Projekt weitere hinzufügen, z. B. __() oder _n() für ngettext(), oder vielleicht eine ausgefallene _r()-Funktion, die gettext() und sprintf() Aufrufe verbindet. Andere Bibliotheken, wie z. B. Gettext von php-gettext, bieten ebenfalls solche Hilfsfunktionen.

In diesen Fällen musst Du Gettext mitteilen, wie die Strings aus diesen neuen Funktionen extrahiert werden sollen. Keine Sorge, es ist ganz einfach. Es handelt sich lediglich um ein Feld in der .po-Datei bzw. eine Einstellung in Poedit. Im Editor finden Sie diese Option unter “Katalog > Eigenschaften > Quellschlüsselwörter”. Denken Sie daran: Gettext kennt bereits die Standardfunktionen für viele Sprachen. Sei also nicht beunruhigt, wenn die Liste leer erscheint. Du musst dort die Spezifikationen Deiner neuen Funktionen in einem bestimmten Format einfügen:

Nachdem Du diese neuen Regeln in die .po-Datei aufgenommen hast, werden Deine neuen Zeichenfolgen durch einen neuen Scan genauso einfach wie zuvor eingefügt.

Verweise

Back to Top

Dependency Injection (Abhängigkeiten-Injektion)

From Wikipedia:

Dependency Injection ist ein Software-Entwurfsmuster, welches das Entfernen fest codierter Abhängigkeiten ermöglicht und deren Änderung sowohl zur Laufzeit als auch zur Kompilierzeit ermöglicht.

Dieses Zitat lässt das Konzept viel komplizierter klingen, als es tatsächlich ist. Dependency Injection stellt einer Komponente ihre Abhängigkeiten entweder durch Konstruktor-Injektion, Methodenaufrufe oder das Setzen von Eigenschaften zur Verfügung. So einfach ist das.

Basic Concept

We can demonstrate the concept with a simple, yet naive example.

Here we have a Database class that requires an adapter to speak to the database. We instantiate the adapter in the constructor and create a hard dependency. This makes testing difficult and means the Database class is very tightly coupled to the adapter.

<?php
namespace Database;

class Database
{
    protected $adapter;

    public function __construct()
    {
        $this->adapter = new MySqlAdapter;
    }
}

class MysqlAdapter {}

This code can be refactored to use Dependency Injection and therefore loosen the dependency. Here, we inject the dependency in a constructor and use the constructor property promotion so it is available as a property across the class:

<?php
namespace Database;

class Database
{
    public function __construct(protected MySqlAdapter $adapter)
    {
    }
}

class MysqlAdapter {}

Now we are giving the Database class its dependency rather than creating it itself. We could even create a method that would accept an argument of the dependency and set it that way, or if the $adapter property was public we could set it directly.

Complex Problem

If you have ever read about Dependency Injection then you have probably seen the terms “Inversion of Control” or “Dependency Inversion Principle”. These are the complex problems that Dependency Injection solves.

Inversion of Control

Inversion of Control is as it says, “inverting the control” of a system by keeping organizational control entirely separate from our objects. In terms of Dependency Injection, this means loosening our dependencies by controlling and instantiating them elsewhere in the system.

For years, PHP frameworks have been achieving Inversion of Control, however, the question became, which part of control are we inverting, and where to? For example, MVC frameworks would generally provide a super object or base controller that other controllers must extend to gain access to its dependencies. This is Inversion of Control, however, instead of loosening dependencies, this method simply moved them.

Dependency Injection allows us to more elegantly solve this problem by only injecting the dependencies we need, when we need them, without the need for any hard coded dependencies at all.

S.O.L.I.D.

Single Responsibility Principle

The Single Responsibility Principle is about actors and high-level architecture. It states that “A class should have only one reason to change.” This means that every class should only have responsibility over a single part of the functionality provided by the software. The largest benefit of this approach is that it enables improved code reusability. By designing our class to do just one thing, we can use (or re-use) it in any other program without changing it.

Open/Closed Principle

The Open/Closed Principle is about class design and feature extensions. It states that “Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.” This means that we should design our modules, classes and functions in a way that when a new functionality is needed, we should not modify our existing code but rather write new code that will be used by existing code. Practically speaking, this means that we should write classes that implement and adhere to interfaces, then type-hint against those interfaces instead of specific classes.

The largest benefit of this approach is that we can very easily extend our code with support for something new without having to modify existing code, meaning that we can reduce QA time, and the risk for negative impact to the application is substantially reduced. We can deploy new code, faster, and with more confidence.

Liskov Substitution Principle

The Liskov Substitution Principle is about subtyping and inheritance. It states that “Child classes should never break the parent class’ type definitions.” Or, in Robert C. Martin’s words, “Subtypes must be substitutable for their base types.”

For example, if we have a FileInterface interface which defines an embed() method, and we have Audio and Video classes which both implement the FileInterface interface, then we can expect that the usage of the embed() method will always do the thing that we intend. If we later create a PDF class or a Gist class which implement the FileInterface interface, we will already know and understand what the embed() method will do. The largest benefit of this approach is that we have the ability to build flexible and easily-configurable programs, because when we change one object of a type (e.g., FileInterface) to another we don’t need to change anything else in our program.

Interface Segregation Principle

The Interface Segregation Principle (ISP) is about business-logic-to-clients communication. It states that “No client should be forced to depend on methods it does not use.” This means that instead of having a single monolithic interface that all conforming classes need to implement, we should instead provide a set of smaller, concept-specific interfaces that a conforming class implements one or more of.

For example, a Car or Bus class would be interested in a steeringWheel() method, but a Motorcycle or Tricycle class would not. Conversely, a Motorcycle or Tricycle class would be interested in a handlebars() method, but a Car or Bus class would not. There is no need to have all of these types of vehicles implement support for both steeringWheel() as well as handlebars(), so we should break-apart the source interface.

Dependency Inversion Principle

The Dependency Inversion Principle is about removing hard-links between discrete classes so that new functionality can be leveraged by passing a different class. It states that one should “Depend on Abstractions. Do not depend on concretions.”. Put simply, this means our dependencies should be interfaces/contracts or abstract classes rather than concrete implementations. We can easily refactor the above example to follow this principle.

<?php
namespace Database;

class Database
{
    public function __construct(protected AdapterInterface $adapter)
    {
    }
}

interface AdapterInterface {}

class MysqlAdapter implements AdapterInterface {}

There are several benefits to the Database class now depending on an interface rather than a concretion.

Consider that we are working in a team and the adapter is being worked on by a colleague. In our first example, we would have to wait for said colleague to finish the adapter before we could properly mock it for our unit tests. Now that the dependency is an interface/contract we can happily mock that interface knowing that our colleague will build the adapter based on that contract.

An even bigger benefit to this method is that our code is now much more scalable. If a year down the line we decide that we want to migrate to a different type of database, we can write an adapter that implements the original interface and injects that instead, no more refactoring would be required as we can ensure that the adapter follows the contract set by the interface.

Containers

The first thing you should understand about Dependency Injection Containers is that they are not the same thing as Dependency Injection. A container is a convenience utility that helps us implement Dependency Injection, however, they can be and often are misused to implement an anti-pattern, Service Location. Injecting a DI container as a Service Locator in to your classes arguably creates a harder dependency on the container than the dependency you are replacing. It also makes your code much less transparent and ultimately harder to test.

Most modern frameworks have their own Dependency Injection Container that allows you to wire your dependencies together through configuration. What this means in practice is that you can write application code that is as clean and de-coupled as the framework it is built on.

Further Reading

Back to Top

Datenbanken

Many times your PHP code will use a database to persist information. You have a few options to connect and interact with your database. The recommended option until PHP 5.1.0 was to use native drivers such as mysqli, pgsql, mssql, etc.

Native drivers are great if you are only using one database in your application, but if, for example, you are using MySQL and a little bit of MSSQL, or you need to connect to an Oracle database, then you will not be able to use the same drivers. You’ll need to learn a brand new API for each database — and that can get silly.

MySQL Extension

The mysql extension for PHP is incredibly old and has been superseded by two other extensions:

Not only did development stop long ago on mysql, but it has been officially removed in PHP 7.0.

To save digging into your php.ini settings to see which module you are using, one option is to search for mysql_* in your editor of choice. If any functions such as mysql_connect() and mysql_query() show up, then mysql is in use.

Even if you are not using PHP 7.x or later yet, failing to consider this upgrade as soon as possible will lead to greater hardship when the PHP upgrade does come about. The best option is to replace mysql usage with mysqli or PDO in your applications within your own development schedules so you won’t be rushed later on.

If you are upgrading from mysql to mysqli, beware lazy upgrade guides that suggest you can simply find and replace mysql_* with mysqli_*. Not only is that a gross oversimplification, it misses out on the advantages that mysqli provides, such as parameter binding, which is also offered in PDO.

PDO Extension

PDO is a database connection abstraction library — built into PHP since 5.1.0 — that provides a common interface to talk with many different databases. For example, you can use basically identical code to interface with MySQL or SQLite:

<?php
// PDO + MySQL
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT some_field FROM some_table");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['some_field']);

// PDO + SQLite
$pdo = new PDO('sqlite:/path/db/foo.sqlite');
$statement = $pdo->query("SELECT some_field FROM some_table");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['some_field']);

PDO will not translate your SQL queries or emulate missing features; it is purely for connecting to multiple types of database with the same API.

More importantly, PDO allows you to safely inject foreign input (e.g. IDs) into your SQL queries without worrying about database SQL injection attacks. This is possible using PDO statements and bound parameters.

Let’s assume a PHP script receives a numeric ID as a query parameter. This ID should be used to fetch a user record from a database. This is the wrong way to do this:

<?php
$pdo = new PDO('sqlite:/path/db/users.db');
$pdo->query("SELECT name FROM users WHERE id = " . $_GET['id']); // <-- NO!

This is terrible code. You are inserting a raw query parameter into a SQL query. This will get you hacked in a heartbeat, using a practice called SQL Injection. Just imagine if a hacker passes in an inventive id parameter by calling a URL like http://domain.com/?id=1%3BDELETE+FROM+users. This will set the $_GET['id'] variable to 1;DELETE FROM users which will delete all of your users! Instead, you should sanitize the ID input using PDO bound parameters.

<?php
$pdo = new PDO('sqlite:/path/db/users.db');
$stmt = $pdo->prepare('SELECT name FROM users WHERE id = :id');
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT); // <-- filter your data first (see [Data Filtering](#data_filtering)), especially important for INSERT, UPDATE, etc.
$stmt->bindParam(':id', $id, PDO::PARAM_INT); // <-- Automatically sanitized for SQL by PDO
$stmt->execute();

This is correct code. It uses a bound parameter on a PDO statement. This escapes the foreign input ID before it is introduced to the database preventing potential SQL injection attacks.

For writes, such as INSERT or UPDATE, it’s especially critical to still filter your data first and sanitize it for other things (removal of HTML tags, JavaScript, etc). PDO will only sanitize it for SQL, not for your application.

You should also be aware that database connections use up resources and it was not unheard-of to have resources exhausted if connections were not implicitly closed, however this was more common in other languages. Using PDO you can implicitly close the connection by destroying the object by ensuring all remaining references to it are deleted, i.e. set to NULL. If you don’t do this explicitly, PHP will automatically close the connection when your script ends - unless of course you are using persistent connections.

Interacting with Databases

When developers first start to learn PHP, they often end up mixing their database interaction up with their presentation logic, using code that might look like this:

<ul>
<?php
foreach ($db->query('SELECT * FROM table') as $row) {
    echo "<li>".$row['field1']." - ".$row['field1']."</li>";
}
?>
</ul>

This is bad practice for all sorts of reasons, mainly that it’s hard to debug, hard to test, hard to read and it is going to output a lot of fields if you don’t put a limit on there.

While there are many other solutions to doing this - depending on if you prefer OOP or functional programming - there must be some element of separation.

Consider the most basic step:

<?php
function getAllFoos($db) {
    return $db->query('SELECT * FROM table');
}

$results = getAllFoos($db);
foreach ($results as $row) {
    echo "<li>".$row['field1']." - ".$row['field1']."</li>"; // BAD!!
}

That is a good start. Put those two items in two different files and you’ve got some clean separation.

Create a class to place that method in and you have a “Model”. Create a simple .php file to put the presentation logic in and you have a “View”, which is very nearly MVC - a common OOP architecture for most frameworks.

foo.php

<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4', 'username', 'password');

// Make your model available
include 'models/FooModel.php';

// Create an instance
$fooModel = new FooModel($db);
// Get the list of Foos
$fooList = $fooModel->getAllFoos();

// Show the view
include 'views/foo-list.php';

models/FooModel.php

<?php
class FooModel
{
    public function __construct(protected PDO $db)
    {
    }

    public function getAllFoos() {
        return $this->db->query('SELECT * FROM table');
    }
}

views/foo-list.php

<?php foreach ($fooList as $row): ?>
    <li><?= $row['field1'] ?> - <?= $row['field1'] ?></li>
<?php endforeach ?>

This is essentially the same as what most modern frameworks are doing, albeit a little more manual. You might not need to do all of that every time, but mixing together too much presentation logic and database interaction can be a real problem if you ever want to unit-test your application.

Abstraction Layers

Many frameworks provide their own abstraction layer which may or may not sit on top of PDO. These will often emulate features for one database system that is missing from another by wrapping your queries in PHP methods, giving you actual database abstraction instead of just the connection abstraction that PDO provides. This will of course add a little overhead, but if you are building a portable application that needs to work with MySQL, PostgreSQL and SQLite then a little overhead will be worth it for the sake of code cleanliness.

Some abstraction layers have been built using the PSR-0 or PSR-4 namespace standards so can be installed in any application you like:

Back to Top

Templating (Vorlagen)

Templates provide a convenient way of separating your controller and domain logic from your presentation logic. Templates typically contain the HTML of your application, but may also be used for other formats, such as XML. Templates are often referred to as “views”, which make up part of the second component of the model–view–controller (MVC) software architecture pattern.

Benefits

The main benefit to using templates is the clear separation they create between the presentation logic and the rest of your application. Templates have the sole responsibility of displaying formatted content. They are not responsible for data lookup, persistence or other more complex tasks. This leads to cleaner, more readable code which is especially helpful in a team environment where developers work on the server-side code (controllers, models) and designers work on the client-side code (markup).

Templates also improve the organization of presentation code. Templates are typically placed in a “views” folder, each defined within a single file. This approach encourages code reuse where larger blocks of code are broken into smaller, reusable pieces, often called partials. For example, your site header and footer can each be defined as templates, which are then included before and after each page template.

Finally, depending on the library you use, templates can offer more security by automatically escaping user-generated content. Some libraries even offer sand-boxing, where template designers are only given access to white-listed variables and functions.

Plain PHP Templates

Plain PHP templates are simply templates that use native PHP code. They are a natural choice since PHP is actually a template language itself. That simply means that you can combine PHP code within other code, like HTML. This is beneficial to PHP developers as there is no new syntax to learn, they know the functions available to them, and their code editors already have PHP syntax highlighting and auto-completion built-in. Further, plain PHP templates tend to be very fast as no compiling stage is required.

Every modern PHP framework employs some kind of template system, most of which use plain PHP by default. Outside of frameworks, libraries like Plates or Aura.View make working with plain PHP templates easier by offering modern template functionality such as inheritance, layouts and extensions.

Simple example of a plain PHP template

Using the Plates library.

<?php // user_profile.php ?>

<?php $this->insert('header', ['title' => 'User Profile']) ?>

<h1>User Profile</h1>
<p>Hello, <?=$this->escape($name)?></p>

<?php $this->insert('footer') ?>

Example of plain PHP templates using inheritance

Using the Plates library.

<?php // template.php ?>

<html>
<head>
    <title><?=$title?></title>
</head>
<body>

<main>
    <?=$this->section('content')?>
</main>

</body>
</html>
<?php // user_profile.php ?>

<?php $this->layout('template', ['title' => 'User Profile']) ?>

<h1>User Profile</h1>
<p>Hello, <?=$this->escape($name)?></p>

Compiled Templates

While PHP has evolved into a mature, object oriented language, it hasn’t improved much as a templating language. Compiled templates, like Twig, Brainy, or Smarty*, fill this void by offering a new syntax that has been geared specifically to templating. From automatic escaping, to inheritance and simplified control structures, compiled templates are designed to be easier to write, cleaner to read and safer to use. Compiled templates can even be shared across different languages, Mustache being a good example of this. Since these templates must be compiled there is a slight performance hit, however this is very minimal when proper caching is used.

*While Smarty offers automatic escaping, this feature is NOT enabled by default.

Simple example of a compiled template

Using the Twig library.

{% include 'header.html' with {'title': 'User Profile'} %}

<h1>User Profile</h1>
<p>Hello, {{ name }}</p>

{% include 'footer.html' %}

Example of compiled templates using inheritance

Using the Twig library.

// template.html

<html>
<head>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>

<main>
    {% block content %}{% endblock %}
</main>

</body>
</html>
// user_profile.html

{% extends "template.html" %}

{% block title %}User Profile{% endblock %}
{% block content %}
    <h1>User Profile</h1>
    <p>Hello, {{ name }}</p>
{% endblock %}

Further Reading

Articles & Tutorials

Libraries

Back to Top

Fehler und Exceptions

Fehler

In vielen “exception-heavy” Programmiersprachen wird bei jedem Fehler eine Exception ausgelöst. Dies ist sicherlich eine praktikable Vorgehensweise, PHP hingegen ist “exception-light”. Obwohl es Exceptions gibt und der Kernel diese immer mehr bei der Arbeit mit Objekten verwendet, versucht PHP selbst größtenteils, das Ausführen unabhängig vom Ereignis fortzusetzen, es sei denn, es tritt ein schwerwiegender Fehler (fatal error) auf.

Zum Beispiel:

$ php -a
php > echo $foo;
Notice: Undefined variable: foo in php shell code on line 1

Dies ist nur ein Hinweisfehler, PHP macht problemlos weiter. Dies kann für Benutzer von “exception-heavy” Sprachen verwirrend sein, da beispielsweise der Verweis auf eine fehlende Variable in Python eine Exception auslöst:

$ python
>>> print foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined

Der einzige wirkliche Unterschied besteht darin, dass Python bei jeder Kleinigkeit ausflippt, sodass Entwickler absolut sicher sein können, dass jedes potenzielle Problem oder jeder Grenzfall erkannt wird, während PHP die Verarbeitung fortsetzt, bis etwas Extremes passiert. In diesem Fall wird ein Fehler ausgegeben und gemeldet.

Fehlergrad (Error Severity)

PHP kennt mehrere Schweregrade für Fehler. Die drei häufigsten Meldungstypen sind Fehler, Hinweise und Warnungen. Diese haben unterschiedliche FehlerstufenE_ERROR, E_NOTICE, und E_WARNING. Fehler (Error) sind schwerwiegende Laufzeitfehler, die in der Regel durch Fehler im Code verursacht werden und behoben werden müssen, da sie die Ausführung von PHP verhindern. Hinweise (Notice) sind ratsame Warnmeldungen, die durch Code verursacht werden, der während der Skriptausführung Probleme verursachen kann (die Ausführung wird nicht angehalten). Warnungen sind nicht schwerwiegende Fehler; die Ausführung des Skripts wird nicht angehalten.

Eine weitere Art von Fehlermeldungen, die zur Kompilierzeit gemeldet werden, sind E_STRICT-Meldungen. Diese Meldungen dienen dazu, Änderungen an Deinem Code vorzuschlagen, um optimale Interoperabilität und Vorwärtskompatibilität mit zukünftigen PHP-Versionen zu gewährleisten.

Changing PHP’s Error Reporting Behaviour

Error Reporting can be changed by using PHP settings and/or PHP function calls. Using the built in PHP function error_reporting() you can set the level of errors for the duration of the script execution by passing one of the predefined error level constants, meaning if you only want to see Errors and Warnings - but not Notices - then you can configure that:

<?php
error_reporting(E_ERROR | E_WARNING);

You can also control whether or not errors are displayed to the screen (good for development) or hidden, and logged (good for production). For more information on this check out the Error Reporting section.

Inline Error Suppression

You can also tell PHP to suppress specific errors with the Error Control Operator @. You put this operator at the beginning of an expression, and any error that’s a direct result of the expression is silenced.

<?php
echo @$foo['bar'];

This will output $foo['bar'] if it exists, but will simply return a null and print nothing if the variable $foo or 'bar' key does not exist. Without the error control operator, this expression could create a PHP Notice: Undefined variable: foo or PHP Notice: Undefined index: bar error.

This might seem like a good idea, but there are a few undesirable tradeoffs. PHP handles expressions using an @ in a less performant way than expressions without an @. Premature optimization may be the root of all programming arguments, but if performance is particularly important for your application/library it’s important to understand the error control operator’s performance implications.

Secondly, the error control operator completely swallows the error. The error is not displayed, and the error is not sent to the error log. Also, stock/production PHP systems have no way to turn off the error control operator. While you may be correct that the error you’re seeing is harmless, a different, less harmless error will be just as silent.

If there’s a way to avoid the error suppression operator, you should consider it. For example, our code above could be rewritten like this:

<?php
// Null Coalescing Operator
echo $foo['bar'] ?? '';

One instance where error suppression might make sense is where fopen() fails to find a file to load. You could check for the existence of the file before you try to load it, but if the file is deleted after the check and before the fopen() (which might sound impossible, but it can happen) then fopen() will return false and throw an error. This is potentially something PHP should resolve, but is one case where error suppression might seem like the only valid solution.

Earlier we mentioned there’s no way in a stock PHP system to turn off the error control operator. However, Xdebug has an xdebug.scream ini setting which will disable the error control operator. You can set this via your php.ini file with the following.

xdebug.scream = On

You can also set this value at runtime with the ini_set function

<?php
ini_set('xdebug.scream', '1')

This is most useful when you’re debugging code and suspect an informative error is suppressed. Use scream with care, and as a temporary debugging tool. There’s lots of PHP library code that may not work with the error control operator disabled.

ErrorException

PHP is perfectly capable of being an “exception-heavy” programming language, and only requires a few lines of code to make the switch. Basically you can throw your “errors” as “exceptions” using the ErrorException class, which extends the Exception class.

This is a common practice implemented by a large number of modern frameworks such as Symfony and Laravel. In debug mode (or dev mode) both of these frameworks will display a nice and clean stack trace.

There are also some packages available for better error and exception handling and reporting. Like Whoops!, which comes with the default installation of Laravel and can be used in any framework as well.

By throwing errors as exceptions in development you can handle them better than the usual result, and if you see an exception during development you can wrap it in a catch statement with specific instructions on how to handle the situation. Each exception you catch instantly makes your application that little bit more robust.

More information on this and details on how to use ErrorException with error handling can be found at ErrorException Class.

Exceptions

Exceptions are a standard part of most popular programming languages, but they are often overlooked by PHP programmers. Languages like Ruby are extremely Exception heavy, so whenever something goes wrong such as a HTTP request failing, or a DB query goes wrong, or even if an image asset could not be found, Ruby (or the gems being used) will throw an exception to the screen meaning you instantly know there is a mistake.

PHP itself is fairly lax with this, and a call to file_get_contents() will usually just get you a FALSE and a warning. Many older PHP frameworks like CodeIgniter will just return a false, log a message to their proprietary logs and maybe let you use a method like $this->upload->get_error() to see what went wrong. The problem here is that you have to go looking for a mistake and check the docs to see what the error method is for this class, instead of having it made extremely obvious.

Another problem is when classes automatically throw an error to the screen and exit the process. When you do this you stop another developer from being able to dynamically handle that error. Exceptions should be thrown to make a developer aware of an error; they then can choose how to handle this. E.g.:

<?php
$email = new Fuel\Email;
$email->subject('My Subject');
$email->body('How the heck are you?');
$email->to('guy@example.com', 'Some Guy');

try
{
    $email->send();
}
catch(Fuel\Email\ValidationFailedException $e)
{
    // The validation failed
}
catch(Fuel\Email\SendingFailedException $e)
{
    // The driver could not send the email
}
finally
{
    // Executed regardless of whether an exception has been thrown, and before normal execution resumes
}

SPL Exceptions

The generic Exception class provides very little debugging context for the developer; however, to remedy this, it is possible to create a specialized Exception type by sub-classing the generic Exception class:

<?php
class ValidationException extends Exception {}

This means you can add multiple catch blocks and handle different Exceptions differently. This can lead to the creation of a lot of custom Exceptions, some of which could have been avoided using the SPL Exceptions provided in the SPL extension.

If for example you use the __call() Magic Method and an invalid method is requested then instead of throwing a standard Exception which is vague, or creating a custom Exception just for that, you could just throw new BadMethodCallException;.

Back to Top

Sicherheit

The best resource I’ve found on PHP security is The 2018 Guide to Building Secure PHP Software by Paragon Initiative.

Web Application Security

It is very important for every PHP developer to learn the basics of web application security, which can be broken down into a handful of broad topics:

  1. Code-data separation.
    • When data is executed as code, you get SQL Injection, Cross-Site Scripting, Local/Remote File Inclusion, etc.
    • When code is printed as data, you get information leaks (source code disclosure or, in the case of C programs, enough information to bypass ASLR).
  2. Application logic.
    • Missing authentication or authorization controls.
    • Input validation.
  3. Operating environment.
    • PHP versions.
    • Third party libraries.
    • The operating system.
  4. Cryptography weaknesses.

There are bad people ready and willing to exploit your web application. It is important that you take necessary precautions to harden your web application’s security. Luckily, the fine folks at The Open Web Application Security Project (OWASP) have compiled a comprehensive list of known security issues and methods to protect yourself against them. This is a must read for the security-conscious developer. Survive The Deep End: PHP Security by Padraic Brady is also another good web application security guide for PHP.

Password Hashing

Eventually everyone builds a PHP application that relies on user login. Usernames and passwords are stored in a database and later used to authenticate users upon login.

It is important that you properly hash passwords before storing them. Hashing and encrypting are two very different things that often get confused.

Hashing is an irreversible, one-way function. This produces a fixed-length string that cannot be feasibly reversed. This means you can compare a hash against another to determine if they both came from the same source string, but you cannot determine the original string. If passwords are not hashed and your database is accessed by an unauthorized third-party, all user accounts are now compromised.

Unlike hashing, encryption is reversible (provided you have the key). Encryption is useful in other areas, but is a poor strategy for securely storing passwords.

Passwords should also be individually salted by adding a random string to each password before hashing. This prevents dictionary attacks and the use of “rainbow tables” (a reverse list of cryptographic hashes for common passwords.)

Hashing and salting are vital as often users use the same password for multiple services and password quality can be poor.

Additionally, you should use a specialized password hashing algorithm rather than fast, general-purpose cryptographic hash function (e.g. SHA256). The short list of acceptable password hashing algorithms (as of June 2018) to use are:

Fortunately, nowadays PHP makes this easy.

Hashing passwords with password_hash

In PHP 5.5 password_hash() was introduced. At this time it is using BCrypt, the strongest algorithm currently supported by PHP. It will be updated in the future to support more algorithms as needed though. The password_compat library was created to provide forward compatibility for PHP >= 5.3.7.

Below we hash a string, and then check the hash against a new string. Because our two source strings are different (‘secret-password’ vs. ‘bad-password’) this login will fail.

<?php
require 'password.php';

$passwordHash = password_hash('secret-password', PASSWORD_DEFAULT);

if (password_verify('bad-password', $passwordHash)) {
    // Correct Password
} else {
    // Wrong password
}

password_hash() takes care of password salting for you. The salt is stored, along with the algorithm and “cost”, as part of the hash. password_verify() extracts this to determine how to check the password, so you don’t need a separate database field to store your salts.

Data Filtering

Never ever (ever) trust foreign input introduced to your PHP code. Always sanitize and validate foreign input before using it in code. The filter_var() and filter_input() functions can sanitize text and validate text formats (e.g. email addresses).

Foreign input can be anything: $_GET and $_POST form input data, some values in the $_SERVER superglobal, and the HTTP request body via fopen('php://input', 'r'). Remember, foreign input is not limited to form data submitted by the user. Uploaded and downloaded files, session values, cookie data, and data from third-party web services are foreign input, too.

While foreign data can be stored, combined, and accessed later, it is still foreign input. Every time you process, output, concatenate, or include data in your code, ask yourself if the data is filtered properly and can it be trusted.

Data may be filtered differently based on its purpose. For example, when unfiltered foreign input is passed into HTML page output, it can execute HTML and JavaScript on your site! This is known as Cross-Site Scripting (XSS) and can be a very dangerous attack. One way to avoid XSS is to sanitize all user-generated data before outputting it to your page by removing HTML tags with the strip_tags() function or escaping characters with special meaning into their respective HTML entities with the htmlentities() or htmlspecialchars() functions.

Another example is passing options to be executed on the command line. This can be extremely dangerous (and is usually a bad idea), but you can use the built-in escapeshellarg() function to sanitize the executed command’s arguments.

One last example is accepting foreign input to determine a file to load from the filesystem. This can be exploited by changing the filename to a file path. You need to remove "/", "../", null bytes, or other characters from the file path so it can’t load hidden, non-public, or sensitive files.

Sanitization

Sanitization removes (or escapes) illegal or unsafe characters from foreign input.

For example, you should sanitize foreign input before including the input in HTML or inserting it into a raw SQL query. When you use bound parameters with PDO, it will sanitize the input for you.

Sometimes it is required to allow some safe HTML tags in the input when including it in the HTML page. This is very hard to do and many avoid it by using other more restricted formatting like Markdown or BBCode, although whitelisting libraries like HTML Purifier exist for this reason.

See Sanitization Filters

Unserialization

It is dangerous to unserialize() data from users or other untrusted sources. Doing so can allow malicious users to instantiate objects (with user-defined properties) whose destructors will be executed, even if the objects themselves aren’t used. You should therefore avoid unserializing untrusted data.

Use a safe, standard data interchange format such as JSON (via json_decode and json_encode) if you need to pass serialized data to the user.

Validation

Validation ensures that foreign input is what you expect. For example, you may want to validate an email address, a phone number, or age when processing a registration submission.

See Validation Filters

Configuration Files

When creating configuration files for your applications, best practices recommend that one of the following methods be followed:

Register Globals

NOTE: As of PHP 5.4.0 the register_globals setting has been removed and can no longer be used. This is only included as a warning for anyone in the process of upgrading a legacy application.

When enabled, the register_globals configuration setting makes several types of variables (including ones from $_POST, $_GET and $_REQUEST) available in the global scope of your application. This can easily lead to security issues as your application cannot effectively tell where the data is coming from.

For example: $_GET['foo'] would be available via $foo, which can override variables that have been declared.

If you are using PHP < 5.4.0 make sure that register_globals is off.

Error Reporting

Error logging can be useful in finding the problem spots in your application, but it can also expose information about the structure of your application to the outside world. To effectively protect your application from issues that could be caused by the output of these messages, you need to configure your server differently in development versus production (live).

Development

To show every possible error during development, configure the following settings in your php.ini:

display_errors = On
display_startup_errors = On
error_reporting = -1
log_errors = On

Passing in the value -1 will show every possible error, even when new levels and constants are added in future PHP versions. The E_ALL constant also behaves this way as of PHP 5.4. - php.net

The E_STRICT error level constant was introduced in 5.3.0 and is not part of E_ALL, however it became part of E_ALL in 5.4.0. What does this mean? In terms of reporting every possible error in version 5.3 it means you must use either -1 or E_ALL | E_STRICT.

Reporting every possible error by PHP version

Production

To hide errors on your production environment, configure your php.ini as:

display_errors = Off
display_startup_errors = Off
error_reporting = E_ALL
log_errors = On

With these settings in production, errors will still be logged to the error logs for the web server, but will not be shown to the user. For more information on these settings, see the PHP manual:

Back to Top

Testen

Writing automated tests for your PHP code is considered a best practice and can lead to well-built applications. Automated tests are a great tool for making sure your application does not break when you are making changes or adding new functionality and should not be ignored.

There are several different types of testing tools (or frameworks) available for PHP, which use different approaches - all of which are trying to avoid manual testing and the need for large Quality Assurance teams, just to make sure recent changes didn’t break existing functionality.

Test Driven Development

From Wikipedia:

Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes a failing automated test case that defines a desired improvement or new function, then produces code to pass that test and finally refactors the new code to acceptable standards. Kent Beck, who is credited with having developed or ‘rediscovered’ the technique, stated in 2003 that TDD encourages simple designs and inspires confidence.

There are several different types of testing that you can do for your application:

Unit Testing

Unit Testing is a programming approach to ensure functions, classes and methods are working as expected, from the point you build them all the way through the development cycle. By checking values going in and out of various functions and methods, you can make sure the internal logic is working correctly. By using Dependency Injection and building “mock” classes and stubs you can verify that dependencies are correctly used for even better test coverage.

When you create a class or function you should create a unit test for each behavior it must have. At a very basic level you should make sure it errors if you send it bad arguments and make sure it works if you send it valid arguments. This will help ensure that when you make changes to this class or function later on in the development cycle that the old functionality continues to work as expected. The only alternative to this would be var_dump() in a test.php, which is no way to build an application - large or small.

The other use for unit tests is contributing to open source. If you can write a test that shows broken functionality (i.e. fails), then fix it, and show the test passing, patches are much more likely to be accepted. If you run a project which accepts pull requests then you should suggest this as a requirement.

PHPUnit is the de-facto testing framework for writing unit tests for PHP applications, but there are several alternatives:

Integration Testing

From Wikipedia:

Integration testing (sometimes called Integration and Testing, abbreviated “I&T”) is the phase in software testing in which individual software modules are combined and tested as a group. It occurs after unit testing and before validation testing. Integration testing takes as its input modules that have been unit tested, groups them in larger aggregates, applies tests defined in an integration test plan to those aggregates, and delivers as its output the integrated system ready for system testing.

Many of the same tools that can be used for unit testing can be used for integration testing as many of the same principles are used.

Functional Testing

Sometimes also known as acceptance testing, functional testing consists of using tools to create automated tests that actually use your application instead of just verifying that individual units of code are behaving correctly and that individual units can speak to each other correctly. These tools typically work using real data and simulating actual users of the application.

Functional Testing Tools

Behavior Driven Development

There are two different types of Behavior-Driven Development (BDD): SpecBDD and StoryBDD. SpecBDD focuses on technical behavior of code, while StoryBDD focuses on business or feature behaviors or interactions. PHP has frameworks for both types of BDD.

With StoryBDD, you write human-readable stories that describe the behavior of your application. These stories can then be run as actual tests against your application. The framework used in PHP applications for StoryBDD is Behat, which is inspired by Ruby’s Cucumber project and implements the Gherkin DSL for describing feature behavior.

With SpecBDD, you write specifications that describe how your actual code should behave. Instead of testing a function or method, you are describing how that function or method should behave. PHP offers the PHPSpec framework for this purpose. This framework is inspired by the RSpec project for Ruby.

Complementary Testing Tools

Besides individual testing and behavior driven frameworks, there are also a number of generic frameworks and helper libraries useful for any preferred approach taken.

Back to Top

Server und Deployment

PHP-Anwendungen können auf verschiedene Weise auf Produktionswebservern bereitgestellt und ausgeführt werden.

Platform as a Service (PaaS)

PaaS provides the system and network architecture necessary to run PHP applications on the web. This means little to no configuration for launching PHP applications or PHP frameworks.

Recently PaaS has become a popular method for deploying, hosting, and scaling PHP applications of all sizes. You can find a list of PHP PaaS “Platform as a Service” providers in our resources section.

Virtual or Dedicated Servers

If you are comfortable with systems administration, or are interested in learning it, virtual or dedicated servers give you complete control of your application’s production environment.

nginx and PHP-FPM

PHP, via PHP’s built-in FastCGI Process Manager (FPM), pairs really nicely with nginx, which is a lightweight, high-performance web server. It uses less memory than Apache and can better handle more concurrent requests. This is especially important on virtual servers that don’t have much memory to spare.

Apache and PHP

PHP and Apache have a long history together. Apache is wildly configurable and has many available modules to extend functionality. It is a popular choice for shared servers and an easy setup for PHP frameworks and open source apps like WordPress. Unfortunately, Apache uses more resources than nginx by default and cannot handle as many visitors at the same time.

Apache has several possible configurations for running PHP. The most common and easiest to setup is the prefork MPM with mod_php. While it isn’t the most memory efficient, it is the simplest to get working and to use. This is probably the best choice if you don’t want to dig too deeply into the server administration aspects. Note that if you use mod_php you MUST use the prefork MPM.

Alternatively, if you want to squeeze more performance and stability out of Apache then you can take advantage of the same FPM system as nginx and run the worker MPM or event MPM with mod_fastcgi or mod_fcgid. This configuration will be significantly more memory efficient and much faster but it is more work to set up.

If you are running Apache 2.4 or later, you can use mod_proxy_fcgi to get great performance that is easy to setup.

Shared Servers

PHP has shared servers to thank for its popularity. It is hard to find a host without PHP installed, but be sure it’s the latest version. Shared servers allow you and other developers to deploy websites to a single machine. The upside to this is that it has become a cheap commodity. The downside is that you never know what kind of a ruckus your neighboring tenants are going to create; loading down the server or opening up security holes are the main concerns. If your project’s budget can afford to avoid shared servers, you should.

Make sure your shared servers are offering the latest versions of PHP.

Building and Deploying your Application

If you find yourself doing manual database schema changes or running your tests manually before updating your files (manually), think twice! With every additional manual task needed to deploy a new version of your app, the chances for potentially fatal mistakes increase. Whether you’re dealing with a simple update, a comprehensive build process or even a continuous integration strategy, build automation is your friend.

Among the tasks you might want to automate are:

Deployment Tools

Deployment tools can be described as a collection of scripts that handle common tasks of software deployment. The deployment tool is not a part of your software, it acts on your software from ‘outside’.

There are many open source tools available to help you with build automation and deployment, some are written in PHP others aren’t. This shouldn’t hold you back from using them, if they’re better suited for the specific job. Here are a few examples:

Phing can control your packaging, deployment or testing process from within a XML build file. Phing (which is based on Apache Ant) provides a rich set of tasks usually needed to install or update a web application and can be extended with additional custom tasks, written in PHP. It’s a solid and robust tool and has been around for a long time, however the tool could be perceived as a bit old fashioned because of the way it deals with configuration (XML files).

Capistrano is a system for intermediate-to-advanced programmers to execute commands in a structured, repeatable way on one or more remote machines. It is pre-configured for deploying Ruby on Rails applications, however you can successfully deploy PHP systems with it. Successful use of Capistrano depends on a working knowledge of Ruby and Rake.

Ansistrano is a couple of Ansible roles to easily manage the deployment process (deploy and rollback) for scripting applications such as PHP, Python and Ruby. It’s an Ansible port for Capistrano. It’s been used by quite a lot of PHP companies already.

Deployer is a deployment tool written in PHP. It’s simple and functional. Features include running tasks in parallel, atomic deployment and keeping consistency between servers. Recipes of common tasks for Symfony, Laravel, Zend Framework and Yii are available. Younes Rafie’s article Easy Deployment of PHP Applications with Deployer is a great tutorial for deploying your application with the tool.

Magallanes is another tool written in PHP with simple configuration done in YAML files. It has support for multiple servers and environments, atomic deployment, and has some built in tasks that you can leverage for common tools and frameworks.

Further reading:

Server Provisioning

Managing and configuring servers can be a daunting task when faced with many servers. There are tools for dealing with this so you can automate your infrastructure to make sure you have the right servers and that they’re configured properly. They often integrate with the larger cloud hosting providers (Amazon Web Services, Heroku, DigitalOcean, etc) for managing instances, which makes scaling an application a lot easier.

Ansible is a tool that manages your infrastructure through YAML files. It’s simple to get started with and can manage complex and large scale applications. There is an API for managing cloud instances and it can manage them through a dynamic inventory using certain tools.

Puppet is a tool that has its own language and file types for managing servers and configurations. It can be used in a master/client setup or it can be used in a “master-less” mode. In the master/client mode the clients will poll the central master(s) for new configuration on set intervals and update themselves if necessary. In the master-less mode you can push changes to your nodes.

Chef is a powerful Ruby based system integration framework that you can build your whole server environment or virtual boxes with. It integrates well with Amazon Web Services through their service called OpsWorks.

Further reading:

Continuous Integration

Continuous Integration is a software development practice where members of a team integrate their work frequently, usually each person integrates at least daily — leading to multiple integrations per day. Many teams find that this approach leads to significantly reduced integration problems and allows a team to develop cohesive software more rapidly.

– Martin Fowler

There are different ways to implement continuous integration for PHP. Travis CI has done a great job of making continuous integration a reality even for small projects. Travis CI is a hosted continuous integration service. It can be integrated with GitHub and offers support for many languages including PHP. GitHub has continuous integration workflows with GitHub Actions.

Further reading:

Back to Top

Virtualisierung

Running your application on different environments in development and production can lead to strange bugs popping up when you go live. It’s also tricky to keep different development environments up to date with the same version for all libraries used when working with a team of developers.

If you are developing on Windows and deploying to Linux (or anything non-Windows) or are developing in a team, you should consider using a virtual machine. This sounds tricky, but besides the widely known virtualization environments like VMware or VirtualBox, there are additional tools that may help you setting up a virtual environment in a few easy steps.

Vagrant

Vagrant helps you build your virtual boxes on top of the known virtual environments and will configure these environments based on a single configuration file. These boxes can be set up manually, or you can use “provisioning” software such as Puppet or Chef to do this for you. Provisioning the base box is a great way to ensure that multiple boxes are set up in an identical fashion and removes the need for you to maintain complicated “set up” command lists. You can also “destroy” your base box and recreate it without many manual steps, making it easy to create a “fresh” installation.

Vagrant creates folders for sharing your code between your host and your virtual machine, which means that you can create and edit your files on your host machine and then run the code inside your virtual machine.

Docker

Docker - a lightweight alternative to a full virtual machine - is so called because it’s all about “containers”. A container is a building block which, in the simplest case, does one specific job, e.g. running a web server. An “image” is the package you use to build the container - Docker has a repository full of them.

A typical LAMP application might have three containers: a web server, a PHP-FPM process and MySQL. As with shared folders in Vagrant, you can leave your application files where they are and tell Docker where to find them.

You can generate containers from the command line (see example below) or, for ease of maintenance, build a docker-compose.yml file for your project specifying which to create and how they communicate with one another.

Docker may help if you’re developing multiple websites and want the separation that comes from installing each on its own virtual machine, but don’t have the necessary disk space or the time to keep everything up to date. It’s efficient: the installation and downloads are quicker, you only need to store one copy of each image however often it’s used, containers need less RAM and share the same OS kernel, so you can have more servers running simultaneously, and it takes a matter of seconds to stop and start them, no need to wait for a full server boot.

Example: Running your PHP Applications in Docker

After installing docker on your machine, you can start a web server with one command. The following will download a fully functional Apache installation with the latest PHP version, map /path/to/your/php/files to the document root, which you can view at http://localhost:8080:

docker run -d --name my-php-webserver -p 8080:80 -v /path/to/your/php/files:/var/www/html/ php:apache

This will initialize and launch your container. -d makes it run in the background. To stop and start it, simply run docker stop my-php-webserver and docker start my-php-webserver (the other parameters are not needed again).

Learn more about Docker

The command above shows a quick way to run a basic server. There’s much more you can do (and thousands of pre-built images in the Docker Hub). Take time to learn the terminology and read the Docker User Guide to get the most from it, and don’t run random code you’ve downloaded without checking it’s safe – unofficial images may not have the latest security patches. If in doubt, stick to the official repositiories.

The PHPDocker.io site will auto-generate all the files you need for a fully-featured LAMP/LEMP stack, including your choice of PHP version and extensions.

Back to Top

Caching

PHP is pretty quick by itself, but bottlenecks can arise when you make remote connections, load files, etc. Thankfully, there are various tools available to speed up certain parts of your application, or reduce the number of times these various time-consuming tasks need to run.

Opcode Cache

When a PHP file is executed, it must first be compiled into opcodes (machine language instructions for the CPU). If the source code is unchanged, the opcodes will be the same, so this compilation step becomes a waste of CPU resources.

An opcode cache prevents redundant compilation by storing opcodes in memory and reusing them on successive calls. It will typically check signature or modification time of the file first, in case there have been any changes.

It’s likely an opcode cache will make a significant speed improvement to your application. Since PHP 5.5 there is one built in - Zend OPcache. Depending on your PHP package/distribution, it’s usually turned on by default - check opcache.enable and the output of phpinfo() to make sure. For earlier versions there’s a PECL extension.

Read more about opcode caches:

Object Caching

There are times when it can be beneficial to cache individual objects in your code, such as with data that is expensive to get or database calls where the result is unlikely to change. You can use object caching software to hold these pieces of data in memory for extremely fast access later on. If you save these items to a data store after you retrieve them, then pull them directly from the cache for following requests, you can gain a significant improvement in performance as well as reduce the load on your database servers.

Many of the popular bytecode caching solutions let you cache custom data as well, so there’s even more reason to take advantage of them. APCu and WinCache both provide APIs to save data from your PHP code to their memory cache.

The most commonly used memory object caching systems are APCu and memcached. APCu is an excellent choice for object caching, it includes a simple API for adding your own data to its memory cache and is very easy to setup and use. The one real limitation of APCu is that it is tied to the server it’s installed on. Memcached on the other hand is installed as a separate service and can be accessed across the network, meaning that you can store objects in a hyper-fast data store in a central location and many different systems can pull from it.

Note that whether the cache is shared across PHP processes depends on how PHP is used. When running PHP via PHP-FPM, the cache is shared across all processes of all pools. When running PHP as a (Fast-)CGI application inside your webserver, the cache is not shared, i.e every PHP process will have its own APCu data. When running PHP on the command line, the cache is not shared and will only exist for the duration of the command, so you have to be mindful of your situation and goals. You might want to consider using memcached instead, as it’s not tied to the PHP processes.

In a networked configuration APCu will usually outperform memcached in terms of access speed, but memcached will be able to scale up faster and further. If you do not expect to have multiple servers running your application, or do not need the extra features that memcached offers then APCu is probably your best choice for object caching.

Example logic using APCu:

<?php
// check if there is data saved as 'expensive_data' in cache
$data = apcu_fetch('expensive_data');
if ($data === false) {
    // data is not in cache; save result of expensive call for later use
    apcu_add('expensive_data', $data = get_expensive_data());
}

print_r($data);

Back to Top

Documenting your Code

PHPDoc

PHPDoc is an informal standard for commenting PHP code. There are a lot of different tags available. The full list of tags and examples can be found at the PHPDoc manual.

Below is an example of how you might document a class with a few methods;

<?php
/**
 * @author A Name <a.name@example.com>
 * @link https://docs.phpdoc.org/
 */
class DateTimeHelper
{
    /**
     * @param mixed $anything Anything that we can convert to a \DateTime object
     *
     * @throws \InvalidArgumentException
     *
     * @return \DateTime
     */
    public function dateTimeFromAnything($anything)
    {
        $type = gettype($anything);

        switch ($type) {
            // Some code that tries to return a \DateTime object
        }

        throw new \InvalidArgumentException(
            "Failed Converting param of type '{$type}' to DateTime object"
        );
    }

    /**
     * @param mixed $date Anything that we can convert to a \DateTime object
     *
     * @return void
     */
    public function printISO8601Date($date)
    {
        echo $this->dateTimeFromAnything($date)->format('c');
    }

    /**
     * @param mixed $date Anything that we can convert to a \DateTime object
     */
    public function printRFC2822Date($date)
    {
        echo $this->dateTimeFromAnything($date)->format('r');
    }
}

The documentation for the class as a whole has the @author tag and a @link tag. The @author tag is used to document the author of the code and can be repeated for documenting several authors. The @link tag is used to link to a website indicating a relationship between the website and the code.

Inside the class, the first method has a @param tag documenting the type, name and description of the parameter being passed to the method. Additionally it has the @return and @throws tags for documenting the return type, and any exceptions that could be thrown respectively.

The second and third methods are very similar and have a single @param tag as did the first method. The important difference between the second and third methods’ doc block is the inclusion/exclusion of the @return tag. @return void explicitly informs us that there is no return; historically omitting the @return void statement also results in the same (no return) action.

Back to Top

Resources

From the Source

People to Follow

It’s difficult to find interesting and knowledgeable PHP community members when you are first starting out. You can find an abbreviated list of PHP community members to get you started at:

PHP PaaS Providers

Frameworks

Rather than re-invent the wheel, many PHP developers use frameworks to build out web applications. Frameworks abstract away many of the low-level concerns and provide helpful, easy-to-use interfaces to complete common tasks.

You do not need to use a framework for every project. Sometimes plain PHP is the right way to go, but if you do need a framework then there are three main types available:

Micro-frameworks are essentially a wrapper to route a HTTP request to a callback, controller, method, etc as quickly as possible, and sometimes come with a few extra libraries to assist development such as basic database wrappers and the like. They are prominently used to build remote HTTP services.

Many frameworks add a considerable number of features on top of what is available in a micro-framework; these are called Full-Stack Frameworks. These often come bundled with ORMs, Authentication packages, etc.

Component-based frameworks are collections of specialized and single-purpose libraries. Disparate component-based frameworks can be used together to make a micro- or full-stack framework.

Components

As mentioned above “Components” are another approach to the common goal of creating, distributing and implementing shared code. Various component repositories exist, the main two of which are:

Both of these repositories have command line tools associated with them to help the installation and upgrade processes, and have been explained in more detail in the Dependency Management section.

There are also component-based frameworks and component-vendors that offer no framework at all. These projects provide another source of packages which ideally have little to no dependencies on other packages, or specific frameworks.

For example, you can use the FuelPHP Validation package, without needing to use the FuelPHP framework itself.

Laravel’s Illuminate components will become better decoupled from the Laravel framework. For now, only the components best decoupled from the Laravel framework are listed above.

Other Useful Resources

Cheatsheets

More best practices

News around the PHP and web development communities

You can subscribe to weekly newsletters to keep yourself informed on new libraries, latest news, events and general announcements, as well as additional resources being published every now and then:

There are also Weeklies on other platforms you might be interested in; here’s a list of some.

PHP universe

Video Tutorials

YouTube Channels

Books

There are many PHP books; sadly some are now quite old and no longer accurate. In particular, avoid books on “PHP 6”, a version that will now never exist. The next major release of PHP after 5.6 was “PHP 7”, partly because of this.

This section aims to be a living document for recommended books on PHP development in general. If you would like your book to be added, send a PR and it will be reviewed for relevancy.

Free Books

Back to Top

Community

The PHP community is as diverse as it is large, and its members are ready and willing to support new PHP programmers. Consider joining your local PHP user group (PUG) or attending larger PHP conferences to learn more about the best practices shown here. You can hang out on IRC in the #phpc channel on irc.libera.chat and follow the @phpc, on Discord, on X or Mastodon. Get out there, meet new developers, learn new topics, and above all, make new friends! Other community resources include StackOverflow.

Read the Official PHP Events Calendar

PHP User Groups

If you live in a larger city, odds are there’s a PHP user group nearby. You can easily find your local PUG at PHP.ug. Alternate sources might be Meetup.com or a search for php user group near me using your favorite search engine (i.e. Google). If you live in a smaller town, there may not be a local PUG; if that’s the case, start one!

Special mention should be made of two global user groups: NomadPHP and PHPWomen. NomadPHP offers twice monthly online user group meetings with presentations by some of the top speakers in the PHP community. PHPWomen is a non-exclusive user group originally targeted towards the women in the PHP world. Membership is open to everyone who supports a more diverse community. PHPWomen provide a network for support, mentorship and education, and generally promote the creating of a “female friendly” and professional atmosphere.

Read about User Groups on the PHP Wiki

PHP Conferences

The PHP community also hosts larger regional and national conferences in many countries around the world. Well-known members of the PHP community usually speak at these larger events, so it’s a great opportunity to learn directly from industry leaders.

Find a PHP Conference

ElePHPants

ElePHPant is that beautiful mascot of the PHP project with an elephant in its design. It was originally designed for the PHP project in 1998 by Vincent Pontier - spiritual father of thousands of elePHPants around the world - and ten years later adorable plush elephant toys came to birth as well. Now elePHPants are present at many PHP conferences and with many PHP developers at their computers for fun and inspiration.

Interview with Vincent Pontier