Alle aktuellen Änderungen: Neue Demo-Endpunkte (/twig-demo, /users-from-db), Container- und Datenbank-Setup, Insomnia-Collection und README aktualisiert
This commit is contained in:
parent
d1eb6993b8
commit
e2836396c1
9 changed files with 273 additions and 21 deletions
51
bin/reset-demo-db.php
Normal file
51
bin/reset-demo-db.php
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
<?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);
|
||||||
|
}
|
||||||
|
|
@ -2,7 +2,9 @@
|
||||||
"name": "mycodebox/mariacore",
|
"name": "mycodebox/mariacore",
|
||||||
"description": "Ein einfacher, PSR-inspirierter PHP-Router",
|
"description": "Ein einfacher, PSR-inspirierter PHP-Router",
|
||||||
"type": "project",
|
"type": "project",
|
||||||
"require": {},
|
"require": {
|
||||||
|
"twig/twig": "^3.23"
|
||||||
|
},
|
||||||
"autoload": {
|
"autoload": {
|
||||||
"psr-4": {
|
"psr-4": {
|
||||||
"MyCodebox\\MariaCore\\": "src/",
|
"MyCodebox\\MariaCore\\": "src/",
|
||||||
|
|
@ -17,7 +19,6 @@
|
||||||
"sort-packages": true,
|
"sort-packages": true,
|
||||||
"process-timeout": 0
|
"process-timeout": 0
|
||||||
},
|
},
|
||||||
"require-dev": {},
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
|
|
|
||||||
BIN
database.sqlite
Normal file
BIN
database.sqlite
Normal file
Binary file not shown.
|
|
@ -4,14 +4,27 @@ namespace App\Controller;
|
||||||
|
|
||||||
use MyCodebox\MariaCore\Http\Request;
|
use MyCodebox\MariaCore\Http\Request;
|
||||||
use MyCodebox\MariaCore\Http\Response;
|
use MyCodebox\MariaCore\Http\Response;
|
||||||
|
use Twig\Environment;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Beispiel-Controller für Begrüßungen.
|
* Beispiel-Controller für Begrüßungen.
|
||||||
*/
|
*/
|
||||||
class HelloController
|
class HelloController
|
||||||
{
|
{
|
||||||
|
protected Environment $twig;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gibt eine HTML-Begrüßung zurück.
|
* Konstruktor mit Twig-Dependency.
|
||||||
|
*
|
||||||
|
* @param Environment $twig
|
||||||
|
*/
|
||||||
|
public function __construct(Environment $twig)
|
||||||
|
{
|
||||||
|
$this->twig = $twig;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gibt eine HTML-Begrüßung mit Twig-Template zurück.
|
||||||
*
|
*
|
||||||
* @param Request $request
|
* @param Request $request
|
||||||
* @param array $params
|
* @param array $params
|
||||||
|
|
@ -19,8 +32,8 @@ class HelloController
|
||||||
*/
|
*/
|
||||||
public function greet(Request $request, array $params): Response
|
public function greet(Request $request, array $params): Response
|
||||||
{
|
{
|
||||||
// Name aus den Route-Parametern holen, gegen XSS absichern
|
$name = $params['name'] ?? 'Gast';
|
||||||
$name = htmlspecialchars($params['name'] ?? 'Gast');
|
$html = $this->twig->render('hello.html.twig', ['name' => $name]);
|
||||||
return (new Response())->withHtml("<h1>Hallo aus dem Controller, {$name}!</h1>");
|
return (new Response())->withHtml($html);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -70,27 +70,39 @@
|
||||||
"headers": [],
|
"headers": [],
|
||||||
"_type": "request"
|
"_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",
|
"_id": "req_user",
|
||||||
|
|
||||||
"parentId": "fld_demo",
|
"parentId": "fld_demo",
|
||||||
|
|
||||||
"name": "User Info (mit ID)",
|
"name": "User Info (mit ID)",
|
||||||
|
|
||||||
"method": "GET",
|
"method": "GET",
|
||||||
|
|
||||||
"url": "{{ base_url }}/user/42",
|
"url": "{{ base_url }}/user/42",
|
||||||
|
|
||||||
"body": {},
|
"body": {},
|
||||||
|
|
||||||
"parameters": [],
|
"parameters": [],
|
||||||
|
|
||||||
"headers": [],
|
"headers": [],
|
||||||
|
|
||||||
"_type": "request"
|
"_type": "request"
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
"_id": "req_forward_demo",
|
"_id": "req_forward_demo",
|
||||||
"parentId": "fld_demo",
|
"parentId": "fld_demo",
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,44 @@
|
||||||
<?php
|
<?php
|
||||||
|
|
||||||
// ===========================================
|
// Composer Autoloader
|
||||||
// Bootstrap & Router-Setup für Demo-Anwendung
|
|
||||||
// ===========================================
|
|
||||||
|
|
||||||
// Composer Autoloader laden
|
|
||||||
require_once __DIR__ . '/../../vendor/autoload.php';
|
require_once __DIR__ . '/../../vendor/autoload.php';
|
||||||
|
|
||||||
use MyCodebox\MariaCore\Http\Request;
|
use MyCodebox\MariaCore\Http\Request;
|
||||||
use MyCodebox\MariaCore\Http\Response;
|
use MyCodebox\MariaCore\Http\Response;
|
||||||
use MyCodebox\MariaCore\Router;
|
use MyCodebox\MariaCore\Router;
|
||||||
use MyCodebox\MariaCore\Cache\RouteCache;
|
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-Instanz erstellen
|
||||||
|
// -------------------------------------------------
|
||||||
$router = new Router();
|
$router = new Router();
|
||||||
|
|
||||||
// Globale Middleware (wird bei jedem Request ausgeführt)
|
// Globale Middleware (wird bei jedem Request ausgeführt)
|
||||||
|
|
@ -41,7 +67,16 @@ require __DIR__ . '/../routes/web.php';
|
||||||
$routeCache = new RouteCache(__DIR__ . '/../../cache/routes.json');
|
$routeCache = new RouteCache(__DIR__ . '/../../cache/routes.json');
|
||||||
$routeCache->write($router->routes);
|
$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 erzeugen und dispatchen
|
||||||
|
|
||||||
$request = new Request();
|
$request = new Request();
|
||||||
$response = $router->dispatch($request);
|
$response = $router->dispatch($request);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -34,6 +34,35 @@ $router->get('/protected', function (Request $request, array $params) {
|
||||||
|
|
||||||
$router->get('/hello/{name}', [HelloController::class, 'greet'])->name('hello');
|
$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) {
|
$router->get('/user/{id}', function (Request $request, array $params) use ($router) {
|
||||||
$id = $params['id'] ?? null;
|
$id = $params['id'] ?? null;
|
||||||
$profileUrl = $router->url('user.profile', ['id' => $id]);
|
$profileUrl = $router->url('user.profile', ['id' => $id]);
|
||||||
|
|
|
||||||
19
example/templates/hello.html.twig
Normal file
19
example/templates/hello.html.twig
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
<!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>
|
||||||
92
src/Container.php
Normal file
92
src/Container.php
Normal file
|
|
@ -0,0 +1,92 @@
|
||||||
|
<?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);
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Reference in a new issue