Compare commits

..

No commits in common. "e2836396c169cd9420245079215d92c563265b08" and "801ce59233f72571ae64c98a12b0ab27bf2e070e" have entirely different histories.

18 changed files with 215 additions and 1113 deletions

145
AGENDS.md
View file

@ -2,138 +2,39 @@
## Aufgaben & ToDos für MariaCore Router-Framework
### Geplante Features (Stand: ✔️ = erledigt, 2024-06-15)
### Geplante Features
1. **Middleware-Unterstützung** ✔️
- Globale Middleware ✔️
- Routen-spezifische Middleware ✔️
1. **Middleware-Unterstützung**
- Globale Middleware
- Routen-spezifische Middleware
2. **Route-Gruppen und Prefixes** ✔️
- Gruppierung von Routen mit gemeinsamen Prefixes und/oder Middleware ✔️
2. **Route-Gruppen und Prefixes**
- Gruppierung von Routen mit gemeinsamen Prefixes und/oder Middleware
3. **HTTP-Methoden erweitern** ✔️
- Unterstützung für PUT, DELETE, PATCH, OPTIONS ✔️
3. **HTTP-Methoden erweitern**
- Unterstützung für PUT, DELETE, PATCH, OPTIONS
4. **Named Routes & URL-Generator** ✔️
- Routen können benannt werden ✔️
- URLs können anhand des Namens generiert werden ✔️
4. **Named Routes & URL-Generator**
- Routen können benannt werden
- URLs können anhand des Namens generiert werden
5. **Parameter-Validierung & Constraints** ✔️
- Parameter können mit Regex validiert werden ✔️
5. **Parameter-Validierung & Constraints**
- Parameter können mit Regex validiert werden
6. **Error Handling & Custom Error Pages** ✔️
- Zentrale Fehlerbehandlung, eigene Fehlerseiten/JSON ✔️
6. **Error Handling & Custom Error Pages**
- Zentrale Fehlerbehandlung, eigene Fehlerseiten/JSON
7. **Request- und Response-Helper** ✔️
- Methoden wie withRedirect, withHtml, withText, withDownload, withJson, withStatus, withHeader, withBody ✔️
7. **Request- und Response-Helper**
- Methoden wie withRedirect, withHtml, withText, withDownload
8. **Controller-Support** ✔️
- Handler können auch als Controller@Methode, [Controller::class, 'methode'] oder Closure angegeben werden ✔️
8. **Controller-Support**
- Handler können auch als Controller@Methode angegeben werden
9. **Routen-Caching** ✔️
- Optional: Routenstruktur als Cache speichern und laden (Meta-Cache, keine Closures) ✔️
- CLI-Tool zur Verwaltung ✔️
9. **Routen-Caching**
- Optional: Routenstruktur als Cache speichern und laden
10. **Routen-Dokumentation** ✔️
- Automatische Übersicht aller Routen als HTML oder JSON ✔️
- CLI-Listing ✔️
---
### Erweiterte/Neue Features (2024-06-XX)
- **Internes Forwarding:**
- Mit `Router::forward()` können Handler/Middleware intern auf andere benannte Routen weiterleiten (inkl. Query-Params). ✔️
- **Mini-Container:**
- Beispiel für einfachen Dependency Injection Container in README.md ✔️
- **CLI-Tools:**
- Routen-Cache löschen, neu bauen, anzeigen, alle Routen auflisten ✔️
- **Response-Methoden-Übersicht:**
- Alle Response-Helper und Getter in README.md dokumentiert ✔️
---
### Core-Status & optionale Features
**Aktueller Stand (Juni 2024):**
- Routing-Logik (GET, POST, PUT, PATCH, DELETE, OPTIONS)
- Middleware (global, pro Route, pro Gruppe)
- Route-Gruppen & Prefixes
- Named Routes & URL-Generator
- Parameter-Constraints (Regex)
- Controller- und Closure-Support
- Response-Helper (JSON, HTML, Text, Redirect, Download, Status, Header, Body)
- Zentrale Fehlerbehandlung (custom Error Handler)
- Routen-Caching (Meta-Cache, keine Closures)
- Internes Forwarding (kein Redirect)
- CLI-Tool für Cache & Routen
- Klar strukturierte Klassen, PHPDoc, Typisierung
**Optional für die Zukunft:**
- PSR-7/PSR-15-Kompatibilität (echte Interfaces für Requests, Responses, Middleware)
- PSR-11-Container-Integration (setContainer/getContainer im Router, automatische Controller-Instanziierung)
- Route-Parameter-Defaults
- Subdomain/Host-basiertes Routing (Multi-Tenancy)
- Mehrsprachigkeit/Locale-Routing (z.B. /de/, /en/)
- Routenpriorität/Sortierung
- Events/Hooks (vor/nach Dispatch, Middleware etc.)
- Request/Response-Validierung (z.B. JSON-Schema)
- Rate Limiting/Throttling (API-Limits)
- Tests im Core (Unit/Integration)
---
### Offene ToDos & Ideen für später
- **Remote-Repository & Push:**
- Push zu origin/dev, falls noch nicht geschehen (Remote ggf. einrichten).
- **Automatisierte Tests:**
- Unit- und Integrationstests für Router, Middleware, Response, etc. ergänzen.
- Teststrategie und Coverage festlegen.
- **CI/CD-Setup:**
- Automatisierte Checks (z.B. GitHub Actions, GitLab CI) für Linting, Tests, Composer Validate.
- **Release/Tag:**
- Stand als Release markieren, ggf. Tagging einführen.
- **Composer-Paket:**
- Veröffentlichung als Composer-Package prüfen/vorbereiten.
- **OpenAPI/Swagger:**
- Maschinenlesbare API-Dokumentation (OpenAPI/Swagger) ergänzen.
- **Demo/Framework-Trennung:**
- Demo-App und Framework ggf. in getrennte Repos auslagern.
- **Security-Review:**
- Optional: Security-Check (Header, Input-Validierung, etc.), falls öffentlich genutzt.
- **Weitere Doku/Beispiele:**
- Noch mehr Praxisbeispiele, Security-Hinweise, FAQ, Troubleshooting.
---
<!-- Stand Juni 2024: Alle Kernfeatures und Erweiterungen umgesetzt. Weitere Verbesserungen und Ideen siehe oben. -->
### Notizen
- Die Reihenfolge der Implementierung kann je nach Komplexität und Abhängigkeiten angepasst werden.
- Nach jedem Feature-Block erfolgt ein kurzer Test und eine Dokumentation im AGENDS.md.
- Bei größeren Änderungen: Branch-Strategie beachten (dev, test, main).
- **Abschluss Stand:** Alle Kernfeatures und Erweiterungen Stand Juni 2024 umgesetzt und dokumentiert. 🎉
---
### Sonstiges
- Ideen, Bugs, Refactoring-Vorschläge oder offene Fragen können hier ebenfalls notiert werden.
- Für Feedback und Review: Siehe Git-Commits und Pull Requests.
10. **Routen-Dokumentation**
- Automatische Übersicht aller Routen als HTML oder JSON
---

View file

@ -1,54 +0,0 @@
# CHANGELOG
## [Unreleased] – 2024-06
### Refactoring & Verbesserungen
#### Allgemein
- Umfassendes Refactoring und Aufräumen des gesamten Projekts (`src/`, `example/`, `bin/`).
- Kommentare und PHPDoc in allen Kernklassen und Beispiel-Controllern vereinheitlicht und präzisiert.
- Konsistente Typisierung und bessere Lesbarkeit im gesamten Code.
- Fehlerbehandlung und Robustheit in allen Komponenten verbessert.
#### src/
- **Router.php**
- Fehlerausgaben und Exception-Handling bei Controller-Handlern verbessert.
- Middleware-Stack-Fehlerausgabe verständlicher gestaltet.
- Kommentare und PHPDoc auf Deutsch und klarer formuliert.
- Kleinere Vereinheitlichungen bei Prefix- und Middleware-Behandlung.
- **Http/Response.php**
- Fehlerbehandlung bei JSON-Encoding in `withJson()` ergänzt (liefert Fehlerobjekt und Status 500 bei Encoding-Problemen).
- PHPDoc für Response-Helper vereinheitlicht.
- **Http/Request.php**
- Header-Namen werden jetzt immer als Kleinbuchstaben gespeichert und abgefragt (Case-Insensitivity).
- PHPDoc ergänzt und vereinheitlicht.
- Doppelte Dokumentation entfernt.
- **Cache/RouteCache.php**
- Fehlerbehandlung beim Schreiben, Lesen und Löschen der Cache-Datei verbessert (RuntimeException bei Problemen).
- PHPDoc ergänzt und vereinheitlicht.
#### example/
- **routes/web.php**
- Struktur und Kommentare vereinheitlicht (Abschnitte für GET/POST/PUT/…).
- Überflüssige Leerzeilen entfernt, Beispielrouten klar gegliedert.
- Middleware- und Gruppenbeispiele besser kommentiert.
- **public/index.php**
- Klarere Struktur und Kommentare für Bootstrap, Middleware und Error-Handler.
- Logging und Fehlerausgabe als Beispiel hervorgehoben.
- **app/Controller/HelloController.php & RoutesController.php**
- PHPDoc und Kommentare ergänzt.
- Typisierung der Methodenparameter und Rückgaben klargestellt.
- HTML-Ausgabe in `RoutesController` robuster (XSS-Schutz durch `htmlspecialchars` mit Encoding).
#### bin/
- **bin/route-cache**
- Kommentare und Usage-Abschnitt klarer und einheitlicher gestaltet.
- Fehlerausgaben für alle Befehle verbessert (Ausgabe auf STDERR, Exit-Code bei Fehlern).
- Code-Formatierung und Robustheit erhöht (alle Dateioperationen und dynamischen Includes in Try/Catch-Blöcke).
- Handler-String-Erkennung bei der Listen-Ausgabe robuster gemacht.
---
## [Vorherige Versionen]
- Initiale Implementierung des MariaCore Routers mit PSR-Prinzipien, Middleware, Named Routes, Controller-Support, Response-Helpern, internem Forwarding, Meta-Cache und CLI-Tool.
---

395
README.md
View file

@ -20,61 +20,6 @@ Ein schlanker, moderner PHP-Router mit Middleware, Named Routes, Controller-Supp
---
## Middleware
Middleware kann global, pro Route oder für ganze Gruppen verwendet werden. Sie eignet sich für Authentifizierung, Logging, CORS, etc.
### Globale Middleware (für alle Routen)
```php
<?php
$router->addMiddleware(function (Request $request, callable $next) {
// Beispiel: Logging
error_log('[Router] ' . $request->getMethod() . ' ' . $request->getUri());
// Weiter zur nächsten Middleware/Handler
return $next($request);
});
```
### Middleware pro Route
```php
<?php
$router->get('/protected', function (Request $request, array $params) {
return (new Response())->withJson(['message' => 'Du bist authentifiziert!']);
}, [
function (Request $request, callable $next) {
if ($request->getHeader('x-auth') !== 'geheim') {
return (new Response())->withJson(['error' => 'Nicht autorisiert'], 401);
}
return $next($request);
}
]);
```
### Middleware für Gruppen
```php
<?php
$router->group('/admin', function ($router) {
$router->get('/dashboard', function (Request $request, array $params) {
return (new Response())->withJson(['dashboard' => 'Admin stats here']);
});
}, [
function (Request $request, callable $next) {
if ($request->getHeader('x-admin') !== 'true') {
return (new Response())->withJson(['error' => 'Admin-Bereich!'], 403);
}
return $next($request);
}
]);
```
---
## Schnellstart
### 1. Installation
@ -113,44 +58,20 @@ $router->get('/user/{id}', function (Request $request, array $params) use ($rout
'profile_url' => $profileUrl
]);
})->name('user.profile');
// Route mit Middleware
$router->get('/protected', function (Request $request, array $params) {
return (new Response())->withJson(['message' => 'Du bist authentifiziert!']);
}, [
function (Request $request, callable $next) {
if ($request->getHeader('x-auth') !== 'geheim') {
return (new Response())->withJson(['error' => 'Nicht autorisiert'], 401);
}
return $next($request);
}
]);
```
## API/CRUD-Beispiel
Ein vollständiges Beispiel für eine kleine REST-API mit allen HTTP-Methoden:
```php
<?php
$router->group('/api', function ($router) {
// Alle User (GET)
$router->get('/users', function (Request $request, array $params) {
return (new Response())->withJson(['users' => ['Alice', 'Bob', 'Charlie']]);
});
// User anlegen (POST)
$router->post('/users', function (Request $request, array $params) {
return (new Response())->withJson(['message' => 'User created'], 201);
});
// User aktualisieren (PUT)
$router->put('/users/{id}', function (Request $request, array $params) {
return (new Response())->withJson(['message' => 'User updated', 'id' => $params['id'] ?? null]);
});
// User Teil-Update (PATCH)
$router->patch('/users/{id}', function (Request $request, array $params) {
return (new Response())->withJson(['message' => 'User partially updated', 'id' => $params['id'] ?? null]);
});
// User löschen (DELETE)
$router->delete('/users/{id}', function (Request $request, array $params) {
return (new Response())->withJson(['message' => 'User deleted', 'id' => $params['id'] ?? null]);
});
// OPTIONS für CORS/Preflight
$router->options('/users', function (Request $request, array $params) {
return (new Response())
->withHeader('Allow', 'GET,POST,PUT,DELETE,PATCH,OPTIONS')
->withJson(['allow' => 'GET,POST,PUT,DELETE,PATCH,OPTIONS']);
});
});
```
---
## Named Routes & URL-Generator
@ -167,6 +88,7 @@ $router->get('/article/{slug}', function (Request $request, array $params) {
$url = $router->url('article.show', ['slug' => 'mein-artikel']);
// Ergebnis: /article/mein-artikel
```
---
## Route-Gruppen & Prefixes
@ -179,73 +101,23 @@ $router->group('/api', function ($router) {
$router->post('/users', [UserController::class, 'create']);
});
```
---
## Internes Forwarding (Router::forward) vs. Redirect
Mit `Router::forward()` kannst du innerhalb eines Handlers oder einer Middleware intern auf eine andere benannte Route weiterleiten – inklusive Übergabe von Route-Parametern und Query-Params. **Der Client bekommt davon nichts mit (kein Redirect, keine neue URL im Browser).**
Im Gegensatz dazu erzeugt `withRedirect()` einen echten HTTP-Redirect (Status 3xx), bei dem der Client einen neuen Request an die Ziel-URL macht.
### Beispiel für internes Forwarding
```php
<?php
// In example/routes/web.php
// Leitet intern auf die named route 'user.profile' weiter, id=99, foo=bar
$router->get('/forward-demo', function (Request $request, array $params) use ($router) {
return $router->forward('user.profile', ['id' => 99], ['foo' => 'bar']);
});
```
Das Ergebnis ist identisch zu einem Aufruf von `/user/99?foo=bar`, aber ohne dass der Client weitergeleitet wird.
---
## Response-Methoden
Die Response-Klasse bietet folgende Methoden:
## Response-Helper
| Methode | Beschreibung | Beispiel |
|--------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------|-----------------------------------------------|
| `withJson($data, $statusCode = 200, $jsonOptions = 0)` | Antwort als JSON, setzt Content-Type automatisch | `$response->withJson(['ok' => true])` |
| `withHtml($html, $statusCode = 200)` | Antwort als HTML, setzt Content-Type automatisch | `$response->withHtml('<h1>Hello</h1>')` |
| `withText($text, $statusCode = 200)` | Antwort als Plaintext, setzt Content-Type automatisch | `$response->withText('Nur Text')` |
| `withRedirect($location, $statusCode = 302)` | HTTP-Redirect, setzt Location-Header und Statuscode | `$response->withRedirect('/login')` |
| `withDownload($filename, $content, $contentType = 'application/octet-stream')` | Antwort als Datei-Download, setzt passende Header | `$response->withDownload('file.txt', 'Inhalt')`|
| `withStatus($code)` | Antwort mit anderem HTTP-Statuscode (z.B. 404, 500) | `$response->withStatus(404)` |
| `withHeader($name, $value)` | Setzt einen beliebigen HTTP-Header | `$response->withHeader('X-Test', 'Wert')` |
| `withBody($body)` | Antwort mit anderem Body | `$response->withBody('Neuer Body')` |
| `getStatusCode()` | Gibt den aktuellen HTTP-Statuscode zurück | `$response->getStatusCode()` |
| `getHeaders()` | Gibt alle gesetzten Header als Array zurück | `$response->getHeaders()` |
| `getBody()` | Gibt den aktuellen Body zurück | `$response->getBody()` |
| `send()` | Sendet die Antwort an den Client (wird meist automatisch am Ende aufgerufen) | `$response->send()` |
### Beispiele
```php
<?php
// JSON-Antwort
return (new Response())->withJson(['success' => true]);
// HTML-Antwort
return (new Response())->withHtml('<h1>Hallo Welt!</h1>');
// Plaintext
return (new Response())->withJson(['ok' => true]);
return (new Response())->withHtml('<h1>Hello</h1>');
return (new Response())->withText('Nur Text');
// Redirect
return (new Response())->withRedirect('/login');
// Datei-Download
return (new Response())->withDownload('beispiel.txt', 'Dateiinhalt', 'text/plain');
// Statuscode ändern
return (new Response())->withStatus(404)->withText('Nicht gefunden');
// Header setzen
return (new Response())->withHeader('X-Custom', 'Wert')->withJson(['ok' => true]);
// Statuscode, Header und Body abfragen
$status = $response->getStatusCode();
$headers = $response->getHeaders();
$body = $response->getBody();
return (new Response())->withDownload('datei.txt', 'Inhalt...');
```
---
@ -292,79 +164,49 @@ function (Request $request, array $params)
---
## API-Dokumentation
## Response-Methoden
Hier findest du eine Übersicht aller Beispiel- und API-Endpunkte, wie sie in der Demo-Anwendung (`example/routes/web.php`) und Insomnia-Collection enthalten sind.
Die Response-Klasse bietet folgende Methoden:
### Übersicht
| Methode | Beschreibung | Beispiel |
|--------------------------|-----------------------------------------------------------------------------------------------|-----------------------------------------------|
| `withJson($data, $statusCode = 200)` | Antwort als JSON, setzt Content-Type automatisch | `$response->withJson(['ok' => true])` |
| `withHtml($html, $statusCode = 200)` | Antwort als HTML, setzt Content-Type automatisch | `$response->withHtml('<h1>Hello</h1>')` |
| `withText($text, $statusCode = 200)` | Antwort als Plaintext, setzt Content-Type automatisch | `$response->withText('Nur Text')` |
| `withRedirect($location, $statusCode = 302)` | HTTP-Redirect, setzt Location-Header und Statuscode | `$response->withRedirect('/login')` |
| `withDownload($filename, $content, $contentType = 'application/octet-stream')` | Antwort als Datei-Download, setzt passende Header | `$response->withDownload('file.txt', 'Inhalt')`|
| `withStatus($code)` | Antwort mit anderem HTTP-Statuscode (z.B. 404, 500) | `$response->withStatus(404)` |
| `withHeader($name, $value)`| Setzt einen beliebigen HTTP-Header | `$response->withHeader('X-Test', 'Wert')` |
| `withBody($body)` | Antwort mit anderem Body | `$response->withBody('Neuer Body')` |
| `send()` | Sendet die Antwort an den Client (wird meist automatisch am Ende aufgerufen) | `$response->send()` |
| Methode | Pfad | Beschreibung | Auth/Middleware | Beispiel-Response |
|---------|-----------------------------|----------------------------------------------|------------------------|-------------------------------|
| GET | `/` | Startseite (HTML) | – | `<h1>Willkommen!</h1>` |
| GET | `/routes` | Alle Routen als JSON | – | JSON-Array aller Routen |
| GET | `/routes.html` | Alle Routen als HTML-Tabelle | – | HTML-Tabelle |
| GET | `/hello/{name}` | Begrüßung mit Name (HTML) | – | `<h1>Hallo aus dem Controller, ...</h1>` |
| GET | `/twig-demo` | Twig-Demo: Rendert ein Template mit Config | – | HTML-Seite mit Begrüßung und Info |
| GET | `/users-from-db` | User-Liste aus SQLite-Datenbank (Demo) | – | `{ "users": [ ... ] }` |
| GET | `/user/{id}` | User-Info als JSON | – | `{ "user_id": 42, ... }` |
| GET | `/protected` | Geschützte Route (JSON) | Header: `x-auth` | 401/200 JSON |
| GET | `/go-home` | Redirect zur Startseite | – | HTTP 302 Redirect |
| GET | `/forward-demo` | Internes Forwarding auf `/user/99` | – | `{ "user_id": 99, ... }` |
| GET | `/plain` | Plaintext-Antwort | – | `Dies ist eine reine Textantwort.` |
| GET | `/download` | Datei-Download | – | Download |
| POST | `/users` | User anlegen (Demo) | – | `{ "message": "User created" }`|
| POST | `/submit` | Formular-Submit (Demo) | – | HTML |
| PUT | `/users/{id}` | User aktualisieren (Demo) | – | `{ "message": "User updated", ... }` |
| PATCH | `/users/{id}` | User Teil-Update (Demo) | – | `{ "message": "User partially updated", ... }` |
| DELETE | `/users/{id}` | User löschen (Demo) | – | `{ "message": "User deleted", ... }` |
| OPTIONS | `/users` | Unterstützte Methoden für /users | – | Header + JSON |
### Beispiele
#### API-Gruppe `/api`
```php
<?php
| Methode | Pfad | Beschreibung | Beispiel-Response |
|---------|-----------------------|---------------------------------|-------------------------------|
| GET | `/api/users` | Alle User (Demo) | `{ "users": [...] }` |
| POST | `/api/users` | User anlegen (Demo) | `{ "message": "User created" }`|
| PUT | `/api/users/{id}` | User aktualisieren (Demo) | `{ "message": "User updated", "id": ... }` |
| PATCH | `/api/users/{id}` | User Teil-Update (Demo) | `{ "message": "User partially updated", "id": ... }` |
| PATCH | `/api/users` | Teil-Update aller User (Demo) | `{ "message": "Alle User wurden ..."} ` |
| DELETE | `/api/users/{id}` | User löschen (Demo) | `{ "message": "User deleted", "id": ... }` |
| OPTIONS | `/api/users` | Unterstützte Methoden | Header + JSON |
| GET | `/api/users/{id}` | User-Info (Demo) | `{ "user_id": ..., ... }` |
| OPTIONS | `/api/users/{id}` | Unterstützte Methoden | Header + JSON |
// JSON-Antwort
return (new Response())->withJson(['success' => true]);
#### Admin-Gruppe `/admin`
// HTML-Antwort
return (new Response())->withHtml('<h1>Hallo Welt!</h1>');
| Methode | Pfad | Beschreibung | Auth/Middleware | Beispiel-Response |
|---------|-----------------------|---------------------------------|-------------------------------|-------------------------------|
| GET | `/admin/dashboard` | Admin-Dashboard (Demo) | Header: `x-admin: true` | `{ "dashboard": "Admin stats here" }` |
// Plaintext
return (new Response())->withText('Nur Text');
---
// Redirect
return (new Response())->withRedirect('/login');
### Hinweise
// Datei-Download
return (new Response())->withDownload('beispiel.txt', 'Dateiinhalt', 'text/plain');
- **Parameter:**
Platzhalter wie `{id}` oder `{name}` werden automatisch aus der URL extrahiert und als `$params` übergeben.
- **Middleware:**
Einige Endpunkte (z.B. `/protected`, `/admin/dashboard`) erfordern spezielle Header für Authentifizierung.
- **Response-Formate:**
Die meisten Endpunkte liefern JSON, einige HTML oder Plaintext. Datei-Downloads werden mit passenden Headern ausgeliefert.
- **Twig-Demo:**
Der Pfad `/twig-demo` zeigt, wie ein Twig-Template mit Variablen und Config gerendert wird.
- **SQLite/PDO-Demo:**
Der Pfad `/users-from-db` gibt User-Daten aus der SQLite-Datenbank zurück (Tabelle `users` muss existieren, siehe Setup).
- **Weitere Beispiele und Testmöglichkeiten:**
Siehe die beiliegende Insomnia-Collection (`example/insomnia.json`).
// Statuscode ändern
return (new Response())->withStatus(404)->withText('Nicht gefunden');
---
// Header setzen
return (new Response())->withHeader('X-Custom', 'Wert')->withJson(['ok' => true]);
```
## Insomnia-Collection
Für schnelles Testen und als API-Dokumentation liegt eine Insomnia-Collection bei:
**`example/insomnia.json`**
- Importiere die Datei in Insomnia (oder kompatible Tools), um alle Beispiel- und API-Endpunkte direkt zu testen.
- Die Collection enthält Demo- und API-Requests, passende Header und Beispiel-Bodies.
---
@ -388,22 +230,6 @@ Für schnelles Testen und als API-Dokumentation liegt eine Insomnia-Collection b
- **Alle Routen auflisten:**
`bin/route-cache list`
### CLI-Tool verwenden
Das CLI-Tool findest du unter `bin/route-cache`. Du kannst es so aufrufen:
```bash
php bin/route-cache list
# oder (wenn du es mit chmod +x bin/route-cache unter Linux/MacOS ausführbar gemacht hast)
bin/route-cache list
```
Verfügbare Befehle:
- `build` – Cache neu generieren
- `clear` – Cache löschen
- `show` – Cache anzeigen (JSON)
- `list` – Alle registrierten Routen anzeigen
---
## Projektstruktur
@ -414,8 +240,12 @@ example/ # Demo-Anwendung (Controller, Routen, Public)
bin/ # CLI-Tools
cache/ # Routen-Cache (JSON)
```
---
## Dependency Injection & Mini-Container
Du kannst dein Projekt mit einem einfachen Dependency Injection Container (DI-Container) noch flexibler machen. Damit kannst du Controller, Services oder Middleware automatisch instanziieren und Abhängigkeiten verwalten.
@ -483,131 +313,16 @@ $controller = $container->get(UserController::class);
## Weiterführendes
- **Eigene Controller:** Lege sie unter `example/app/Controller` ab und verwende sie als Handler.
- **Middleware:** Schreibe eigene Middleware als Closure oder Klasse.
- **Tests & Erweiterungen:** Das Framework ist modular und kann leicht erweitert werden.
---
## Template-Engines (z.B. Twig) integrieren
Du kannst beliebige Template-Engines wie [Twig](https://twig.symfony.com/) einfach nutzen – direkt im Handler oder (empfohlen) über einen DI-Container.
### Twig installieren
```bash
composer require twig/twig
```
### Twig im Handler verwenden
```php
<?php
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
$twig = new Environment(new FilesystemLoader(__DIR__ . '/../templates'));
$router->get('/hello/{name}', function (Request $request, array $params) use ($twig) {
$name = $params['name'] ?? 'Gast';
$html = $twig->render('hello.html.twig', ['name' => $name]);
return (new Response())->withHtml($html);
});
```
### Twig im Controller via Container (empfohlen)
```php
<?php
// Registrierung im Container
$container->set(Environment::class, fn($c) => new Environment(
new FilesystemLoader(__DIR__ . '/../templates')
));
// Controller
use Twig\Environment;
class HelloController {
protected Environment $twig;
public function __construct(Environment $twig) {
$this->twig = $twig;
}
public function greet(Request $request, array $params) {
$name = $params['name'] ?? 'Gast';
$html = $this->twig->render('hello.html.twig', ['name' => $name]);
return (new Response())->withHtml($html);
}
}
// Handler-Registrierung
$router->get('/hello/{name}', [HelloController::class, 'greet']);
```
### Twig-Template (z.B. `example/templates/hello.html.twig`)
```twig
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<h1>Hallo, {{ name }}!</h1>
</body>
</html>
```
---
## Datenbank-Anbindung (PDO/Doctrine/...)
Du kannst beliebige Datenbank-Clients (z.B. PDO, Doctrine DBAL, Medoo) direkt im Handler oder – besser – über einen DI-Container nutzen.
**PDO im Handler:**
```php
<?php
$pdo = new PDO('mysql:host=localhost;dbname=demo', 'user', 'pass');
$router->get('/users', function (Request $request, array $params) use ($pdo) {
$users = $pdo->query('SELECT * FROM users')->fetchAll(PDO::FETCH_ASSOC);
return (new Response())->withJson(['users' => $users]);
});
```
**PDO im Controller via Container:**
```php
<?php
$container->set(PDO::class, fn($c) => new PDO('mysql:host=localhost;dbname=demo', 'user', 'pass'));
class UserController {
protected PDO $pdo;
public function __construct(PDO $pdo) { $this->pdo = $pdo; }
public function list(Request $request, array $params) {
$users = $this->pdo->query('SELECT * FROM users')->fetchAll(PDO::FETCH_ASSOC);
return (new Response())->withJson(['users' => $users]);
}
}
$router->get('/users', [UserController::class, 'list']);
```
**Doctrine DBAL im Container:**
```php
<?php
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
$container->set(Connection::class, fn($c) => DriverManager::getConnection([
'url' => 'mysql://user:pass@localhost/demo'
]));
```
---
## Lizenz
MIT

View file

@ -1,51 +0,0 @@
<?php
// bin/reset-demo-db.php
// Setzt die SQLite-Datenbank zurück und legt sie mit Demo-Tabelle 'users' und Beispiel-Daten neu an.
$dbFile = __DIR__ . '/../database.sqlite';
if (file_exists($dbFile)) {
echo "Lösche bestehende Datenbank: $dbFile\n";
if (!unlink($dbFile)) {
echo "Fehler: Konnte alte Datenbank nicht löschen!\n";
exit(1);
}
}
try {
$pdo = new PDO('sqlite:' . $dbFile);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Tabelle anlegen
$pdo->exec("
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE
);
");
// Demo-Daten einfügen
$users = [
['Alice', 'alice@example.com'],
['Bob', 'bob@example.com'],
['Charlie', 'charlie@example.com'],
['Dora', 'dora@example.com'],
['Eve', 'eve@example.com'],
];
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
foreach ($users as $user) {
$stmt->execute($user);
}
echo "SQLite-Datenbank wurde zurückgesetzt und neu erstellt: $dbFile\n";
echo "Tabelle 'users' mit Demo-Daten angelegt.\n";
} catch (Throwable $e) {
echo "Fehler beim Erstellen der Datenbank: " . $e->getMessage() . "\n";
if (file_exists($dbFile)) {
unlink($dbFile);
}
exit(1);
}

View file

@ -1,14 +1,12 @@
#!/usr/bin/env php
<?php
// ===========================================
// MariaCore Router: Route-Cache CLI-Tool
// ===========================================
// Befehle:
// CLI-Tool zur Verwaltung des Routen-Caches für MariaCore Router
// Usage:
// bin/route-cache clear - Cache löschen
// bin/route-cache build - Cache neu generieren (aus routes/web.php)
// bin/route-cache show - Cache anzeigen (JSON)
// bin/route-cache list - Alle registrierten Routen anzeigen
// bin/route-cache list - Alle Routen ausgeben (aus web.php)
require_once __DIR__ . '/../vendor/autoload.php';
@ -21,11 +19,11 @@ $routeCache = new RouteCache($cacheFile);
function printUsage()
{
echo "MariaCore Route Cache CLI\n";
echo "Befehle:\n";
echo "Usage:\n";
echo " route-cache clear - Cache löschen\n";
echo " route-cache build - Cache neu generieren (aus routes/web.php)\n";
echo " route-cache show - Cache anzeigen (JSON)\n";
echo " route-cache list - Alle registrierten Routen anzeigen\n";
echo " route-cache list - Alle Routen ausgeben (aus web.php)\n";
exit(1);
}
@ -33,71 +31,51 @@ $cmd = $argv[1] ?? null;
switch ($cmd) {
case 'clear':
try {
$routeCache->clear();
echo "Route-Cache wurde gelöscht: $cacheFile\n";
} catch (Throwable $e) {
fwrite(STDERR, "Fehler beim Löschen des Caches: " . $e->getMessage() . "\n");
exit(2);
}
$routeCache->clear();
echo "Route-Cache wurde gelöscht: $cacheFile\n";
break;
case 'build':
try {
$router = new Router();
require __DIR__ . '/../example/routes/web.php';
$routeCache->write($router->routes);
echo "Route-Cache wurde neu generiert: $cacheFile\n";
} catch (Throwable $e) {
fwrite(STDERR, "Fehler beim Generieren des Caches: " . $e->getMessage() . "\n");
exit(2);
}
$router = new Router();
require __DIR__ . '/../example/routes/web.php';
$routeCache->write($router->routes);
echo "Route-Cache wurde neu generiert: $cacheFile\n";
break;
case 'show':
try {
$data = $routeCache->read();
if ($data === null) {
echo "Kein Route-Cache gefunden: $cacheFile\n";
exit(1);
}
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
} catch (Throwable $e) {
fwrite(STDERR, "Fehler beim Lesen des Caches: " . $e->getMessage() . "\n");
exit(2);
$data = $routeCache->read();
if ($data === null) {
echo "Kein Route-Cache gefunden: $cacheFile\n";
exit(1);
}
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
break;
case 'list':
try {
$router = new Router();
require __DIR__ . '/../example/routes/web.php';
echo "Alle registrierten Routen:\n";
echo str_pad("METHODE", 8) . str_pad("PFAD", 30) . str_pad("NAME", 25) . "HANDLER\n";
echo str_repeat("-", 80) . "\n";
foreach ($router->routes as $method => $routesArr) {
foreach ($routesArr as $pattern => $info) {
$name = $info['name'] ?? '';
$handler = $info['handler'];
if (is_string($handler)) {
$handlerStr = $handler;
} elseif (is_array($handler)) {
if (isset($handler[0]) && isset($handler[1])) {
$handlerStr = (is_string($handler[0]) ? $handler[0] : (is_object($handler[0]) ? get_class($handler[0]) : '[Objekt]')) . '::' . $handler[1];
} else {
$handlerStr = '[Array]';
}
} elseif ($handler instanceof Closure) {
$handlerStr = 'Closure';
$router = new Router();
require __DIR__ . '/../example/routes/web.php';
echo "Alle registrierten Routen:\n";
echo str_pad("METHODE", 8) . str_pad("PFAD", 30) . str_pad("NAME", 25) . "HANDLER\n";
echo str_repeat("-", 80) . "\n";
foreach ($router->routes as $method => $routesArr) {
foreach ($routesArr as $pattern => $info) {
$name = $info['name'] ?? '';
$handler = $info['handler'];
if (is_string($handler)) {
$handlerStr = $handler;
} elseif (is_array($handler)) {
if (isset($handler[0]) && isset($handler[1])) {
$handlerStr = (is_string($handler[0]) ? $handler[0] : get_class($handler[0])) . '::' . $handler[1];
} else {
$handlerStr = gettype($handler);
$handlerStr = '[Array]';
}
echo str_pad($method, 8) . str_pad($pattern, 30) . str_pad($name, 25) . $handlerStr . "\n";
} elseif ($handler instanceof Closure) {
$handlerStr = 'Closure';
} else {
$handlerStr = gettype($handler);
}
echo str_pad($method, 8) . str_pad($pattern, 30) . str_pad($name, 25) . $handlerStr . "\n";
}
} catch (Throwable $e) {
fwrite(STDERR, "Fehler beim Anzeigen der Routen: " . $e->getMessage() . "\n");
exit(2);
}
break;

View file

@ -2,9 +2,7 @@
"name": "mycodebox/mariacore",
"description": "Ein einfacher, PSR-inspirierter PHP-Router",
"type": "project",
"require": {
"twig/twig": "^3.23"
},
"require": {},
"autoload": {
"psr-4": {
"MyCodebox\\MariaCore\\": "src/",
@ -19,6 +17,7 @@
"sort-packages": true,
"process-timeout": 0
},
"require-dev": {},
"license": "MIT",
"authors": [
{

Binary file not shown.

View file

@ -4,36 +4,12 @@ namespace App\Controller;
use MyCodebox\MariaCore\Http\Request;
use MyCodebox\MariaCore\Http\Response;
use Twig\Environment;
/**
* Beispiel-Controller für Begrüßungen.
*/
class HelloController
{
protected Environment $twig;
/**
* Konstruktor mit Twig-Dependency.
*
* @param Environment $twig
*/
public function __construct(Environment $twig)
public function greet(Request $request, array $params)
{
$this->twig = $twig;
}
/**
* Gibt eine HTML-Begrüßung mit Twig-Template zurück.
*
* @param Request $request
* @param array $params
* @return Response
*/
public function greet(Request $request, array $params): Response
{
$name = $params['name'] ?? 'Gast';
$html = $this->twig->render('hello.html.twig', ['name' => $name]);
return (new Response())->withHtml($html);
$name = htmlspecialchars($params['name'] ?? 'Gast');
return (new Response())->withHtml("<h1>Hallo aus dem Controller, {$name}!</h1>");
}
}

View file

@ -5,34 +5,16 @@ namespace App\Controller;
use MyCodebox\MariaCore\Http\Request;
use MyCodebox\MariaCore\Http\Response;
/**
* Controller für die Anzeige und Ausgabe der registrierten Routen.
*/
class RoutesController
{
/**
* @var mixed Router-Instanz (typischerweise MyCodebox\MariaCore\Router)
*/
protected $router;
/**
* Konstruktor.
*
* @param mixed $router
*/
public function __construct($router)
{
$this->router = $router;
}
/**
* Gibt alle registrierten Routen als JSON zurück.
*
* @param Request $request
* @param array $params
* @return Response
*/
public function json(Request $request, array $params): Response
public function json(Request $request, array $params)
{
$routes = [];
foreach ($this->router->getRoutes() as $method => $paths) {
@ -48,14 +30,7 @@ class RoutesController
return (new Response())->withJson($routes, 200, JSON_PRETTY_PRINT);
}
/**
* Gibt alle registrierten Routen als HTML-Tabelle zurück.
*
* @param Request $request
* @param array $params
* @return Response
*/
public function html(Request $request, array $params): Response
public function html(Request $request, array $params)
{
$routes = [];
foreach ($this->router->getRoutes() as $method => $paths) {
@ -70,8 +45,8 @@ class RoutesController
}
$html = '<h1>Routen-Übersicht</h1><table border="1" cellpadding="5" style="border-collapse:collapse"><tr><th>Method</th><th>Path</th><th>Name</th><th>Middleware</th></tr>';
foreach ($routes as $route) {
$link = '<a href="' . htmlspecialchars($route['path'], ENT_QUOTES, 'UTF-8') . '">' . htmlspecialchars($route['path'], ENT_QUOTES, 'UTF-8') . '</a>';
$html .= '<tr><td>' . htmlspecialchars($route['method'], ENT_QUOTES, 'UTF-8') . '</td><td>' . $link . '</td><td>' . htmlspecialchars($route['name'], ENT_QUOTES, 'UTF-8') . '</td><td>' . (int)$route['middleware_count'] . '</td></tr>';
$link = '<a href="' . htmlspecialchars($route['path']) . '">' . htmlspecialchars($route['path']) . '</a>';
$html .= '<tr><td>' . htmlspecialchars($route['method']) . '</td><td>' . $link . '</td><td>' . htmlspecialchars($route['name']) . '</td><td>' . $route['middleware_count'] . '</td></tr>';
}
$html .= '</table>';
return (new Response())->withHtml($html);

View file

@ -70,28 +70,6 @@
"headers": [],
"_type": "request"
},
{
"_id": "req_twig_demo",
"parentId": "fld_demo",
"name": "Twig-Demo (Template-Rendering)",
"method": "GET",
"url": "{{ base_url }}/twig-demo",
"body": {},
"parameters": [],
"headers": [],
"description": "Rendert ein Twig-Template mit Name und Config-Info.\n\n**Erwartete Antwort:**\nHTML-Seite mit Begrüßung und Info-Text."
},
{
"_id": "req_users_from_db",
"parentId": "fld_demo",
"name": "Users from DB (SQLite/PDO)",
"method": "GET",
"url": "{{ base_url }}/users-from-db",
"body": {},
"parameters": [],
"headers": [],
"description": "Gibt User-Daten aus der SQLite-Datenbank zurück (Tabelle 'users' muss existieren).\n\n**Erwartete Antwort:**\n```\n{\n \"users\": [\n { \"id\": 1, \"name\": \"Alice\", \"email\": \"alice@example.com\" },\n ...\n ]\n}\n```\nBei Fehler: `{ \"error\": \"DB-Fehler\", \"message\": \"...\" }`"
},
{
"_id": "req_user",
"parentId": "fld_demo",
@ -103,20 +81,8 @@
"headers": [],
"_type": "request"
},
{
"_id": "req_forward_demo",
"parentId": "fld_demo",
"name": "Forward-Demo (internes Routing)",
"method": "GET",
"url": "{{ base_url }}/forward-demo",
"body": {},
"parameters": [],
"headers": [],
"description": "Demonstriert internes Routing (Forwarding) auf die named route 'user.profile' mit id=99 und foo=bar als Query-Parameter.\n\n**Erwartete Antwort:**\n```\n{\n \"user_id\": 99,\n \"profile_url\": \"/user/99\"\n}\n```\nDie Query-Parameter sind in der URL sichtbar, aber werden im Handler nicht verwendet."
},
{
"_id": "req_protected_fail",
"parentId": "fld_demo",
"name": "Protected (ohne Auth, sollte 401 liefern)",
"method": "GET",

View file

@ -7,50 +7,21 @@ use MyCodebox\MariaCore\Http\Request;
use MyCodebox\MariaCore\Http\Response;
use MyCodebox\MariaCore\Router;
use MyCodebox\MariaCore\Cache\RouteCache;
use MyCodebox\MariaCore\Container;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
// -------------------------------------------------
// Container-Instanz erstellen und Services registrieren
// -------------------------------------------------
$container = new Container();
// Twig registrieren (Singleton)
$container->set(Environment::class, fn($c) => new Environment(
new FilesystemLoader(__DIR__ . '/../templates')
), true);
// PDO registrieren (Singleton, Beispiel mit SQLite)
$container->set(PDO::class, fn($c) => new PDO('sqlite:' . __DIR__ . '/../../database.sqlite'), true);
// Beispiel: Config als Wert
$container->set('config', [
'app_name' => 'MariaCore Demo',
'debug' => true
]);
// Beispiel: Controller-Registrierung (optional, kann auch automatisch erfolgen)
/*
$container->set(App\Controller\HelloController::class, fn($c) => new App\Controller\HelloController($c->get(Environment::class)));
*/
// -------------------------------------------------
// Router-Instanz erstellen
// -------------------------------------------------
$router = new Router();
// Globale Middleware (wird bei jedem Request ausgeführt)
// Beispiel: Globale Middleware (wird bei jedem Request ausgeführt)
$router->addMiddleware(function (Request $request, callable $next) {
// Logging-Beispiel
error_log('[Router] ' . $request->getMethod() . ' ' . $request->getUri());
// Beispiel: Logging
error_log('Request: ' . $request->getMethod() . ' ' . $request->getUri());
// Weiter zur nächsten Middleware/Handler
return $next($request);
});
// Custom Error Handler (gibt Fehler als JSON zurück)
// Beispiel: Custom Error Handler
$router->setErrorHandler(function (Request $request, Throwable $e) {
// Beispiel: Gib Fehler als JSON zurück, mit Status 500
return (new Response())->withJson([
'error' => 'Fehler im Router',
'message' => $e->getMessage(),
@ -58,25 +29,14 @@ $router->setErrorHandler(function (Request $request, Throwable $e) {
], 500);
});
// -------------------------------------------------
// Routen registrieren (immer web.php laden)
// -------------------------------------------------
// Immer web.php laden (alle Routen, inkl. Closures)
require __DIR__ . '/../routes/web.php';
// Nach dem Registrieren aller Routen: cachebare Infos extrahieren und speichern
$routeCache = new RouteCache(__DIR__ . '/../../cache/routes.json');
$routeCache->write($router->routes);
// Beispiel: Nutzung von Services aus dem Container
// (z.B. in einem Handler, Controller oder Middleware)
/*
$twig = $container->get(Environment::class);
$pdo = $container->get(PDO::class);
$config = $container->get('config');
*/
// Request erzeugen und dispatchen
$request = new Request();
$response = $router->dispatch($request);

View file

@ -6,21 +6,22 @@ use MyCodebox\MariaCore\Http\Response;
use App\Controller\HelloController;
use App\Controller\RoutesController;
// ---------------------------------------------------
// Controller-Instanzen erzeugen
// ---------------------------------------------------
$routesController = new RoutesController($router);
// ---------------------------------------------------
// GET-Routen
// ---------------------------------------------------
$router->get('/', function (Request $request, array $params) {
return (new Response())->withHtml('<h1>Willkommen auf der Startseite!</h1>');
});
$router->get('/routes', [$routesController, 'json']);
$router->get('/routes.html', [$routesController, 'html']);
$router->get('/protected', function (Request $request, array $params) {
return (new Response())->withJson(['message' => 'Du bist authentifiziert!']);
}, [
@ -34,35 +35,6 @@ $router->get('/protected', function (Request $request, array $params) {
$router->get('/hello/{name}', [HelloController::class, 'greet'])->name('hello');
// Twig-Demo: Rendert ein Template mit Name und Config-Wert
$router->get('/twig-demo', function (Request $request, array $params) use ($container) {
/** @var \Twig\Environment $twig */
$twig = $container->get(\Twig\Environment::class);
$config = $container->get('config');
$html = $twig->render('hello.html.twig', [
'name' => 'Twig-Demo',
'info' => 'App: ' . ($config['app_name'] ?? 'n/a')
]);
return (new Response())->withHtml($html);
});
// SQLite/PDO-Demo: Gibt User aus Datenbank zurück (Tabelle users erwartet)
$router->get('/users-from-db', function (Request $request, array $params) use ($container) {
/** @var \PDO $pdo */
$pdo = $container->get(\PDO::class);
$users = [];
try {
$stmt = $pdo->query('SELECT id, name, email FROM users');
$users = $stmt ? $stmt->fetchAll(\PDO::FETCH_ASSOC) : [];
} catch (\Throwable $e) {
return (new Response())->withJson([
'error' => 'DB-Fehler',
'message' => $e->getMessage()
], 500);
}
return (new Response())->withJson(['users' => $users]);
});
$router->get('/user/{id}', function (Request $request, array $params) use ($router) {
$id = $params['id'] ?? null;
$profileUrl = $router->url('user.profile', ['id' => $id]);
@ -76,12 +48,6 @@ $router->get('/go-home', function (Request $request, array $params) {
return (new Response())->withRedirect('/');
});
// Demo: Internes Forwarding auf /user/{id} mit Query-Params
$router->get('/forward-demo', function (Request $request, array $params) use ($router) {
// Leitet intern auf die named route 'user.profile' weiter, id=99, foo=bar
return $router->forward('user.profile', ['id' => 99], ['foo' => 'bar']);
});
$router->get('/plain', function (Request $request, array $params) {
return (new Response())->withText("Dies ist eine reine Textantwort.");
});
@ -91,9 +57,7 @@ $router->get('/download', function (Request $request, array $params) {
return (new Response())->withDownload('beispiel.txt', $content, 'text/plain');
});
// ---------------------------------------------------
// POST-Routen
// ---------------------------------------------------
$router->post('/users', function (Request $request, array $params) {
return (new Response())->withJson(['message' => 'User created'], 201);
});
@ -104,39 +68,27 @@ $router->post('/submit', function (Request $request, array $params) {
return (new Response())->withHtml("<h1>Formular empfangen, Name: {$name}</h1>");
});
// ---------------------------------------------------
// PUT-Routen
// ---------------------------------------------------
$router->put('/users/{id}', function (Request $request, array $params) {
return (new Response())->withJson(['message' => 'User updated', 'id' => $params['id'] ?? null]);
});
// ---------------------------------------------------
// PATCH-Routen
// ---------------------------------------------------
$router->patch('/users/{id}', function (Request $request, array $params) {
return (new Response())->withJson(['message' => 'User partially updated', 'id' => $params['id'] ?? null]);
});
// ---------------------------------------------------
// DELETE-Routen
// ---------------------------------------------------
$router->delete('/users/{id}', function (Request $request, array $params) {
return (new Response())->withJson(['message' => 'User deleted', 'id' => $params['id'] ?? null]);
});
// ---------------------------------------------------
// OPTIONS-Routen
// ---------------------------------------------------
$router->options('/users', function (Request $request, array $params) {
return (new Response())
->withHeader('Allow', 'GET,POST,PUT,DELETE,PATCH,OPTIONS')
->withJson(['allow' => 'GET,POST,PUT,DELETE,PATCH,OPTIONS']);
return (new Response())->withHeader('Allow', 'GET,POST,PUT,DELETE,PATCH,OPTIONS')->withJson(['allow' => 'GET,POST,PUT,DELETE,PATCH,OPTIONS']);
});
// ---------------------------------------------------
// Beispiel für Route-Gruppen und Prefixes (API)
// ---------------------------------------------------
// Beispiel für Route-Gruppen und Prefixes
$router->group('/api', function ($router) {
$router->get('/users', function (Request $request, array $params) {
return (new Response())->withJson(['users' => ['Alice', 'Bob', 'Charlie']]);
@ -154,17 +106,15 @@ $router->group('/api', function ($router) {
return (new Response())->withJson(['message' => 'User deleted', 'id' => $params['id'] ?? null]);
});
$router->options('/users', function (Request $request, array $params) {
return (new Response())
->withHeader('Allow', 'GET,POST,PUT,DELETE,PATCH,OPTIONS')
->withJson(['allow' => 'GET,POST,PUT,DELETE,PATCH,OPTIONS']);
return (new Response())->withHeader('Allow', 'GET,POST,PUT,DELETE,PATCH,OPTIONS')->withJson(['allow' => 'GET,POST,PUT,DELETE,PATCH,OPTIONS']);
});
// PATCH /api/users (Demo-Response für Teil-Update aller User)
// Ergänzung: PATCH /api/users (Demo-Response für Teil-Update aller User)
$router->patch('/users', function (Request $request, array $params) {
return (new Response())->withJson([
'message' => 'Alle User wurden (demo) teilweise aktualisiert.'
]);
});
// GET /api/users/{id}
// Ergänzung: GET /api/users/{id}
$router->get('/users/{id}', function (Request $request, array $params) use ($router) {
$id = $params['id'] ?? null;
$profileUrl = $router->url('user.profile', ['id' => $id]);
@ -173,7 +123,7 @@ $router->group('/api', function ($router) {
'profile_url' => $profileUrl
]);
});
// OPTIONS /api/users/{id}
// Ergänzung: OPTIONS /api/users/{id}
$router->options('/users/{id}', function (Request $request, array $params) {
return (new Response())
->withHeader('Allow', 'GET,POST,PUT,DELETE,PATCH,OPTIONS')
@ -181,9 +131,6 @@ $router->group('/api', function ($router) {
});
});
// ---------------------------------------------------
// Beispiel für Route-Gruppen und Prefixes (Admin)
// ---------------------------------------------------
$router->group('/admin', function ($router) {
$router->get('/dashboard', function (Request $request, array $params) {
return (new Response())->withJson(['dashboard' => 'Admin stats here']);

View file

@ -1,19 +0,0 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<title>Hallo {{ name }}</title>
<style>
body { font-family: sans-serif; background: #f8f8f8; margin: 2em; }
h1 { color: #2c3e50; }
.info { color: #888; margin-top: 2em; }
</style>
</head>
<body>
<h1>Hallo, {{ name|e('html') }}!</h1>
<div class="info">
Dies ist ein Beispiel für ein Twig-Template.<br>
Du kannst beliebige Variablen und Logik verwenden.
</div>
</body>
</html>

View file

@ -3,16 +3,13 @@
namespace MyCodebox\MariaCore\Cache;
/**
* Class RouteCache
* RouteCache
*
* Verwaltet das Caching der Routen-Metadaten als JSON-Datei.
* Cacht nur serialisierbare Handler (Strings, Controller-Arrays), keine Closures!
*/
class RouteCache
{
/**
* @var string Pfad zur Cache-Datei
*/
private string $cacheFile;
/**
@ -55,17 +52,12 @@ class RouteCache
}
}
if (!is_dir(dirname($this->cacheFile))) {
if (!@mkdir(dirname($this->cacheFile), 0777, true) && !is_dir(dirname($this->cacheFile))) {
throw new \RuntimeException('Cache-Verzeichnis konnte nicht erstellt werden: ' . dirname($this->cacheFile));
}
}
$json = json_encode($cache, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
if ($json === false) {
throw new \RuntimeException('Fehler beim Serialisieren der Routen für den Cache.');
}
if (@file_put_contents($this->cacheFile, $json) === false) {
throw new \RuntimeException('Cache-Datei konnte nicht geschrieben werden: ' . $this->cacheFile);
mkdir(dirname($this->cacheFile), 0777, true);
}
file_put_contents(
$this->cacheFile,
json_encode($cache, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
);
}
/**
@ -78,15 +70,7 @@ class RouteCache
if (!file_exists($this->cacheFile)) {
return null;
}
$content = @file_get_contents($this->cacheFile);
if ($content === false) {
throw new \RuntimeException('Cache-Datei konnte nicht gelesen werden: ' . $this->cacheFile);
}
$data = json_decode($content, true);
if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
throw new \RuntimeException('Fehler beim Parsen der Cache-Datei: ' . json_last_error_msg());
}
return $data;
return json_decode(file_get_contents($this->cacheFile), true);
}
/**
@ -97,9 +81,7 @@ class RouteCache
public function clear(): void
{
if (file_exists($this->cacheFile)) {
if (!@unlink($this->cacheFile)) {
throw new \RuntimeException('Cache-Datei konnte nicht gelöscht werden: ' . $this->cacheFile);
}
unlink($this->cacheFile);
}
}
}

View file

@ -1,92 +0,0 @@
<?php
namespace MyCodebox\MariaCore;
use Closure;
use InvalidArgumentException;
/**
* Einfacher, flexibler Dependency Injection Container.
*
* Unterstützt:
* - Factory-Registrierung (immer neue Instanz)
* - Singleton-Registrierung (einmalige Instanz)
* - Direkte Werte/Objekte
* - Lazy Loading (erst bei Bedarf erzeugt)
*
* Beispiel:
* $container->set(PDO::class, fn($c) => new PDO(...), true); // Singleton
* $container->set('config', fn($c) => [...]); // Factory
* $container->set('twig', $twigInstance); // Direktes Objekt
*/
class Container
{
/**
* @var array<string, array{factory: callable, singleton: bool}>
*/
protected array $bindings = [];
/**
* @var array<string, mixed>
*/
protected array $instances = [];
/**
* Registrierung einer Factory oder eines Singleton.
*
* @param string $id
* @param callable|object $factory
* @param bool $singleton
* @return void
*/
public function set(string $id, $factory, bool $singleton = false): void
{
if (is_callable($factory)) {
$this->bindings[$id] = ['factory' => $factory, 'singleton' => $singleton];
} else {
// Direktes Objekt, Array oder Wert
$this->instances[$id] = $factory;
}
}
/**
* Hole eine Instanz (Singleton oder Factory).
*
* @param string $id
* @return mixed
*/
public function get(string $id)
{
// Singleton bereits erzeugt?
if (isset($this->instances[$id])) {
return $this->instances[$id];
}
// Factory vorhanden?
if (isset($this->bindings[$id])) {
$object = ($this->bindings[$id]['factory'])($this);
if ($this->bindings[$id]['singleton']) {
$this->instances[$id] = $object;
}
return $object;
}
// Fallback: Standard-Konstruktor (ohne Abhängigkeiten)
if (class_exists($id)) {
return new $id();
}
throw new InvalidArgumentException("Service oder Klasse '$id' nicht gefunden.");
}
/**
* Prüft, ob ein Service/Binding existiert.
*
* @param string $id
* @return bool
*/
public function has(string $id): bool
{
return isset($this->bindings[$id]) || isset($this->instances[$id]) || class_exists($id);
}
}

View file

@ -4,12 +4,6 @@ namespace MyCodebox\MariaCore\Http;
/**
* Simplified PSR-7-inspired Request class.
*
* @property string $method
* @property string $uri
* @property array $queryParams
* @property array $parsedBody
* @property array $headers
*/
class Request
{
@ -19,11 +13,6 @@ class Request
protected array $parsedBody;
protected array $headers;
/**
* Request constructor.
*
* Initializes the request object from PHP globals.
*/
public function __construct()
{
$this->method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
@ -35,8 +24,6 @@ class Request
/**
* Get the HTTP method.
*
* @return string
*/
public function getMethod(): string
{
@ -45,8 +32,6 @@ class Request
/**
* Get the URI path.
*
* @return string
*/
public function getUri(): string
{
@ -55,8 +40,6 @@ class Request
/**
* Get query parameters.
*
* @return array
*/
public function getQueryParams(): array
{
@ -65,8 +48,6 @@ class Request
/**
* Get parsed body parameters (POST data).
*
* @return array
*/
public function getParsedBody(): array
{
@ -75,9 +56,6 @@ class Request
/**
* Get all HTTP headers as an associative array.
* Header-Namen sind immer klein geschrieben.
*
* @return array
*/
public function getHeaders(): array
{
@ -86,61 +64,27 @@ class Request
/**
* Get a specific header value or null if not found.
* Der Header-Name ist case-insensitive.
*
* @param string $name
* @return string|null
*/
public function getHeader(string $name): ?string
{
$name = strtolower($name);
return $this->headers[$name] ?? null;
}
/**
* Create a Request object with custom parameters (for internal forwarding).
*
* @param array $override ['method' => ..., 'uri' => ..., 'queryParams' => ..., 'parsedBody' => ..., 'headers' => ...]
* @return static
*/
public static function fromGlobalsOverride(array $override = []): self
{
$instance = new self();
if (isset($override['method'])) {
$instance->method = $override['method'];
}
if (isset($override['uri'])) {
$instance->uri = $override['uri'];
}
if (isset($override['queryParams'])) {
$instance->queryParams = $override['queryParams'];
}
if (isset($override['parsedBody'])) {
$instance->parsedBody = $override['parsedBody'];
}
if (isset($override['headers'])) {
// Vereinheitliche Header-Namen auf Kleinbuchstaben
$headers = [];
foreach ($override['headers'] as $key => $value) {
$headers[strtolower($key)] = $value;
foreach ($this->headers as $key => $value) {
if (strtolower($key) === $name) {
return $value;
}
$instance->headers = $headers;
}
return $instance;
return null;
}
/**
* Parse all HTTP headers from $_SERVER.
* Header-Namen werden als Kleinbuchstaben gespeichert.
*
* @return array
*/
protected function parseHeaders(): array
{
$headers = [];
foreach ($_SERVER as $key => $value) {
if (str_starts_with($key, 'HTTP_')) {
$header = strtolower(str_replace('_', '-', substr($key, 5)));
$header = str_replace('_', '-', strtolower(substr($key, 5)));
$headers[$header] = $value;
}
}

View file

@ -179,21 +179,14 @@ class Response
/**
* Return a new response with JSON body and appropriate content type.
*
* @param mixed $data Data to encode as JSON
* @param int $statusCode HTTP status code
* @param int $jsonOptions JSON encoding options
* @param mixed $data
* @param int $statusCode
* @param int $jsonOptions
* @return self
*/
public function withJson(mixed $data, int $statusCode = 200, int $jsonOptions = 0): self
{
$body = json_encode($data, $jsonOptions | JSON_UNESCAPED_UNICODE);
if ($body === false) {
$body = json_encode([
'error' => 'JSON encoding failed',
'message' => json_last_error_msg(),
]);
$statusCode = 500;
}
$clone = clone $this;
$clone->body = $body;
$clone->statusCode = $statusCode;

View file

@ -8,12 +8,12 @@ use MyCodebox\MariaCore\Http\Response;
/**
* Class Router
*
* Leichtgewichtiger, PSR-inspirierter Router mit Middleware, Route-Gruppen, Named Routes und Controller-Support.
* Lightweight PSR-inspired router with middleware, route groups, named routes, and controller support.
*/
class Router
{
/**
* Registrierte Routen, gruppiert nach HTTP-Methode.
* All registered routes, grouped by HTTP method.
* @var array<string, array>
*/
public array $routes = [
@ -23,35 +23,34 @@ class Router
'PATCH' => [],
'DELETE' => [],
'OPTIONS' => [],
// Weitere HTTP-Methoden können hier ergänzt werden
];
/**
* Benannte Routen für URL-Generierung.
* Named routes for URL generation.
* @var array<string, array{method: string, pattern: string}>
*/
public array $namedRoutes = [];
/**
* Stack für Route-Gruppen (Prefix & Middleware).
* Stack for route groups (prefixes and middleware).
* @var array<int, array{prefix: string, middleware: array}>
*/
private array $groupStack = [];
/**
* Globale Middleware, die auf jede Route angewendet wird.
* Global middleware applied to every route.
* @var callable[]
*/
private array $globalMiddleware = [];
/**
* Registriert eine Route mit optionaler Middleware.
* Register a route with optional middleware.
*
* @param string $method
* @param string $pattern
* @param callable|string|array $handler
* @param array $middleware
* @return object RouteRegistrar für Method-Chaining (->name())
* @return object RouteRegistrar for method chaining (->name())
*/
public function add(string $method, string $pattern, callable|string|array $handler, array $middleware = [])
{
@ -72,7 +71,7 @@ class Router
'name' => null,
];
// RouteRegistrar für ->name()
// Return a RouteRegistrar object for method chaining (e.g. ->name())
return new class($this, $method, $pattern) {
private $router;
private $method;
@ -92,47 +91,61 @@ class Router
};
}
/** GET-Route registrieren. */
/**
* Register a GET route.
*/
public function get(string $pattern, callable|string|array $handler, array $middleware = [])
{
return $this->add('GET', $pattern, $handler, $middleware);
}
/** POST-Route registrieren. */
/**
* Register a POST route.
*/
public function post(string $pattern, callable|string|array $handler, array $middleware = [])
{
return $this->add('POST', $pattern, $handler, $middleware);
}
/** PUT-Route registrieren. */
/**
* Register a PUT route.
*/
public function put(string $pattern, callable|string|array $handler, array $middleware = [])
{
return $this->add('PUT', $pattern, $handler, $middleware);
}
/** PATCH-Route registrieren. */
/**
* Register a PATCH route.
*/
public function patch(string $pattern, callable|string|array $handler, array $middleware = [])
{
return $this->add('PATCH', $pattern, $handler, $middleware);
}
/** DELETE-Route registrieren. */
/**
* Register a DELETE route.
*/
public function delete(string $pattern, callable|string|array $handler, array $middleware = [])
{
return $this->add('DELETE', $pattern, $handler, $middleware);
}
/** OPTIONS-Route registrieren. */
/**
* Register an OPTIONS route.
*/
public function options(string $pattern, callable|string|array $handler, array $middleware = [])
{
return $this->add('OPTIONS', $pattern, $handler, $middleware);
}
/** @var callable|null */
/**
* @var callable|null
*/
private $errorHandler = null;
/**
* Setzt einen globalen Error-Handler.
* Set a global error handler.
* @param callable $handler function(Request $request, \Throwable $e): Response
*/
public function setErrorHandler(callable $handler): void
@ -141,7 +154,7 @@ class Router
}
/**
* Dispatcht den Router für den gegebenen Request.
* Dispatch the router for the given request.
*
* @param Request $request
* @return Response
@ -161,7 +174,7 @@ class Router
$regex = $this->convertPatternToRegex($pattern, $params);
if (preg_match($regex, $uri, $matches)) {
// Parameter extrahieren
// Extract parameters
$params = [];
foreach ($matches as $key => $value) {
if (!is_int($key)) {
@ -172,47 +185,36 @@ class Router
$handler = $route['handler'];
$routeMiddleware = $route['middleware'] ?? [];
// Middleware-Stack bauen
// Build middleware stack
$middlewareStack = array_merge(
$this->globalMiddleware,
$routeMiddleware,
[
function ($request) use ($handler, $params) {
// Controller-Support: "Controller@method" oder [ControllerClass, method]
// Controller support: "Controller@method" or [ControllerClass, method]
if (is_string($handler) && strpos($handler, '@') !== false) {
[$class, $method] = explode('@', $handler, 2);
if (class_exists($class)) {
$controller = new $class();
if (method_exists($controller, $method)) {
return $controller->$method($request, $params);
}
throw new \RuntimeException("Methode $method nicht gefunden in Controller $class.");
return $controller->$method($request, $params);
}
throw new \RuntimeException("Controller-Klasse $class nicht gefunden.");
}
if (is_array($handler) && count($handler) === 2 && is_string($handler[0])) {
if (class_exists($handler[0])) {
$controller = new $handler[0]();
$method = $handler[1];
if (method_exists($controller, $method)) {
return $controller->$method($request, $params);
}
throw new \RuntimeException("Methode $method nicht gefunden in Controller {$handler[0]}.");
return $controller->$method($request, $params);
}
throw new \RuntimeException("Controller-Klasse {$handler[0]} nicht gefunden.");
}
if (is_callable($handler)) {
return call_user_func($handler, $request, $params);
}
throw new \RuntimeException('Ungültiger Route-Handler.');
return call_user_func($handler, $request, $params);
}
]
);
// Middleware-Stack ausführen
// Run middleware stack
$runner = function ($request, $middlewareStack, $index = 0) use (&$runner) {
if (!isset($middlewareStack[$index])) {
throw new \RuntimeException('Kein Response-Objekt aus Middleware-Stack zurückgegeben.');
throw new \RuntimeException('Middleware stack exhausted with no response.');
}
$middleware = $middlewareStack[$index];
return $middleware($request, function ($req) use ($runner, $middlewareStack, $index) {
@ -229,7 +231,7 @@ class Router
if ($this->errorHandler) {
return call_user_func($this->errorHandler, $request, $e);
}
// Fallback: Standard-Fehlerausgabe
// Fallback: Standard error output
return (new Response())->withJson([
'error' => 'Internal Server Error',
'message' => $e->getMessage()
@ -238,7 +240,7 @@ class Router
}
/**
* Gibt alle registrierten Routen zurück.
* Get all registered routes.
*
* @return array
*/
@ -248,7 +250,7 @@ class Router
}
/**
* Gruppiert Routen unter einem gemeinsamen Prefix und/oder Middleware.
* Group routes under a common prefix and/or middleware.
*
* @param string $prefix
* @param callable $callback
@ -265,7 +267,9 @@ class Router
array_pop($this->groupStack);
}
/** Benannte Route registrieren (intern). */
/**
* Register a named route (internal use).
*/
public function nameRoute(string $name, string $method, string $pattern): void
{
$this->namedRoutes[$name] = [
@ -275,7 +279,7 @@ class Router
}
/**
* Generiert eine URL für eine benannte Route und Parameter.
* Generate a URL for a named route and parameters.
*
* @param string $name
* @param array $params
@ -287,7 +291,7 @@ class Router
return null;
}
$pattern = $this->namedRoutes[$name]['pattern'];
// Platzhalter im Pattern durch Parameter ersetzen
// Replace placeholders in pattern with parameters
$url = preg_replace_callback('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', function ($matches) use (&$params) {
$key = $matches[1];
if (isset($params[$key])) {
@ -297,7 +301,7 @@ class Router
}
return $matches[0];
}, $pattern);
// Übrige Parameter als Query-String anhängen
// Add remaining params as query string
if (!empty($params)) {
$url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($params);
}
@ -305,7 +309,7 @@ class Router
}
/**
* Globale Middleware hinzufügen.
* Add global middleware.
*
* @param callable $middleware
* @return void
@ -315,7 +319,9 @@ class Router
$this->globalMiddleware[] = $middleware;
}
/** Liefert aktuellen Prefix aus dem Group-Stack. */
/**
* Get current prefix from group stack.
*/
private function getCurrentPrefix(): string
{
$prefix = '';
@ -325,7 +331,9 @@ class Router
return $prefix;
}
/** Liefert alle Middleware aus dem Group-Stack. */
/**
* Get all middleware from group stack.
*/
private function getCurrentGroupMiddleware(): array
{
$all = [];
@ -338,9 +346,9 @@ class Router
}
/**
* Wandelt ein Routen-Pattern in Regex um und extrahiert Parameternamen.
* Convert a route pattern to regex and extract parameter names.
*
* Beispiel: /user/{id} => #^/user/(?P<id>[^/]+)$#
* Example: /user/{id} => #^/user/(?P<id>[^/]+)$#
*
* @param string $pattern
* @param array &$params
@ -348,7 +356,7 @@ class Router
*/
private function convertPatternToRegex(string $pattern, array &$params): string
{
// Constraints erlauben: {param:regex}
// Allow constraints: {param:regex}
$regex = preg_replace_callback(
'#\{([a-zA-Z_][a-zA-Z0-9_]*)(:([^}]+))?\}#',
function ($matches) use (&$params) {
@ -360,30 +368,4 @@ class Router
);
return '#^' . $regex . '$#';
}
/**
* Internes Forwarding auf eine andere benannte Route (ohne HTTP-Redirect).
*
* @param string $routeName
* @param array $params
* @param array $queryParams
* @param string $method
* @return Response
*/
public function forward(string $routeName, array $params = [], array $queryParams = [], string $method = 'GET'): Response
{
$url = $this->url($routeName, $params);
// Query-String anhängen, falls vorhanden
if (!empty($queryParams)) {
$url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($queryParams);
}
// Neues Request-Objekt mit gewünschter URI und Query-Params erzeugen
$forwardedRequest = \MyCodebox\MariaCore\Http\Request::fromGlobalsOverride([
'method' => $method,
'uri' => strtok($url, '?'),
'queryParams' => $queryParams,
]);
// Dispatch an den Router
return $this->dispatch($forwardedRequest);
}
}