zdenekgebauer / ergo
Ergo framework
Requires
- php: >=8.0
- ext-iconv: *
- ext-json: *
- guzzlehttp/psr7: ^2.0
- level-2/dice: ^4.0
- phpmailer/phpmailer: ^6.5
- psr/container: ^2.0
- tracy/tracy: ^2.8
- zdenekgebauer/router: 0.0.2
- zdenekgebauer/sitemap-builder: 0.0.2
- zdenekgebauer/template: 0.0.2
- zdenekgebauer/utils: 0.0.6
Requires (Dev)
- codeception/codeception: ^4.1
- codeception/module-asserts: ^2.0
- codeception/module-phpbrowser: ^2.0
- symfony/process: ^5.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
PHP 8.4+ micro-framework for building web applications. Provides routing, DI container, config, HTTP request/response, i18n, sessions, templating, and events. Application projects extend the framework classes and register modules.
Requirements
- PHP >= 8.4 with
ext-filter,ext-json,ext-mbstringandext-session - Composer
Installation
Ergo is published on Packagist as zdenekgebauer/ergo:
composer require zdenekgebauer/ergo
Composer installs the runtime dependencies listed in the root composer.json. Add
phpmailer/phpmailer only if you use Ergo\Email\Mailer.
Quick start
The www/ directory contains a working example application (Site\* namespace) that demonstrates the intended extension pattern.
your-project/
├── app/
│ ├── config/
│ │ └── config.ini # optional base config
│ ├── lang/
│ │ └── en/ # one directory per language
│ │ └── messages.txt
│ └── templates/
│ └── en/
│ ├── main.htm # page wrapper (must contain [%MAIN_OUTPUT%] and [%HEADER_OUTPUT%])
│ └── home.htm
├── log/
│ └── err/ # Tracy error log directory
└── index.php
index.php:
use Ergo\Environment;
use Ergo\Http\Request;
use Ergo\Http\ResponseEmitter;
require_once __DIR__ . '/vendor/autoload.php';
$config = MyConfig::fromGlobals(__DIR__ . '/../');
Environment::setEnvironment($config);
Environment::setErrorHandlers($config);
$application = new MyApplication($config);
$request = Request::fromGlobals();
new ResponseEmitter()->emit($application->run($request), request: $request);
Architecture
Application
Extend Ergo\Application and register routes and modules in the constructor:
class MyApplication extends \Ergo\Application implements ApplicationInterface
{
public function __construct(private readonly ConfigInterface $siteConfig)
{
parent::__construct($siteConfig);
$this->container->addSubstitute(ApplicationInterface::class, $this);
$application = $this;
$this->registerRoute('/', static fn() => $application->getInstance(HomeController::class)->render(), 'homepage');
$this->registerModule(BlogModule::class);
}
}
Use registerRouteIf(bool $condition, ...) to register a route only when a condition is met (e.g. user is logged in).
Config
// Production entry point — reads $_SERVER for HTTPS detection and hostname
$config = Config::fromGlobals('/var/www/myapp/');
// In tests — pass URL explicitly to avoid touching $_SERVER
$config = new Config('/tmp/test/', 'https://test.example/');
// Load additional .ini file (merged into existing config)
$config->addConfigFile('/path/to/extra.ini');
app/config/config.ini example:
root_url = https://example.com/
mode = production
timezone = Europe/Prague
error_email[] = admin@example.com
The placeholder %root_directory% in .ini values is expanded to dirRoot().
Site\Config (see www/) also auto-loads app/config/<hostname>.ini — useful for per-server overrides without changing the base config.
Controllers
Extend Ergo\Controller\BaseController. The constructor takes only ApplicationInterface; the framework injects $this->request (from getInstance(RequestInterface::class)) and $this->language automatically.
class HomeController extends BaseController
{
public function render(): ResponseInterface
{
$page = new PageComposer($this->application);
$page->pageTemplate($this->application->template('main.htm'));
$page->title('Home');
return $this->html($page->render('<h1>Hello</h1>'));
}
}
Available response helpers (public unless noted as protected):
| Method | Status | Content-Type |
|---|---|---|
content(string $content, string $contentType, HttpStatus) | 200 | custom |
download(string $file, ?string $name, bool $inline, bool $noCache) | 200 | from filename |
downloadData(string $data, string $fileName) | 200 | from filename |
file(string $file, bool $noCache) | 200 | from filename |
html(string $html, HttpStatus) | 200 | text/html |
json(mixed $data, HttpStatus) | 200 | application/json |
redirect(string $url, HttpStatus, array $headers) | 302 | — |
redirectPermanent(string $url, array $headers) | 301 | — |
xml(string $xml, HttpStatus) | 200 | application/xml |
jsonInvalidRequest(string $message) (protected) | 400 | application/json |
jsonNotFound(string $message) (protected) | 404 | application/json |
jsonReload() (protected) | 200 | application/json |
jsonServerError(string $message) (protected) | 500 | application/json |
Project-specific 404 pages
The default Ergo\Controller\DefaultController::render404Page() returns a standalone
HTML document with status 404. It does not load main.htm or invoke modules, so it
also works in applications that register only a subset of the project's modules.
The default homepage still uses main.htm.
To provide a branded 404, extend the default controller in your project:
class ErrorController extends \Ergo\Controller\DefaultController
{
public function render404Page(): \Psr\Http\Message\ResponseInterface
{
$page = new \Ergo\Template\PageComposer($this->application);
$page->pageTemplate($this->application->template('404.htm'));
$page->title('Page not found');
return $this->html($page->render('<h1>Page not found</h1>'), \Ergo\Http\HttpStatus::NOT_FOUND);
}
}
Register it in your application's constructor after parent::__construct($config):
$this->container->addRule(\Ergo\Controller\DefaultController::class, [
'instanceOf' => ErrorController::class,
]);
Use a 404.htm template containing [%MAIN_OUTPUT%] and [%HEADER_OUTPUT%].
If it contains module tags, register those modules in every application using this
controller. This replacement applies to the framework's unmatched-route fallback;
responses returned by matched routes are unchanged. A project overriding
dispatchRequest() must keep or implement its own fallback handling.
HEAD responses
The router matches HEAD against routes registered for GET. The handler runs
normally and constructs the response, including status and headers.
ResponseEmitter suppresses the body for HEAD without reading or modifying its
stream. Content-Length, when supplied, remains the GET representation length.
Pass the current request explicitly when emitting a response, as in the quick-start
example. Existing calls without request: use $_SERVER['REQUEST_METHOD'], or
GET when it is absent. The response returned by Application::run() still has
its body; suppression happens only during emission, including for project overrides
of run() and error responses.
GET handlers should not perform destructive operations. For legacy GET endpoints
that run jobs, reject HEAD before invoking the handler (for example in the project's
dispatchRequest()), returning new Response(405, ['Allow' => 'GET']). Authentication
alone does not stop an authenticated HEAD request from executing the job. New job
endpoints should use POST and appropriate authorization.
JsonPayload
Use Ergo\Http\JsonPayload for structured Ajax responses:
public function handleAjax(): ResponseInterface
{
$name = $this->request->getPost('name');
if ($name === '') {
return $this->jsonInvalidRequest('Parameter "name" is required');
}
$payload = new JsonPayload();
$payload->html = '<p>Hello, ' . htmlspecialchars($name) . '</p>';
$payload->message = 'Success';
$payload->with('name', $name)->with('data', ['key' => 'value']);
return $this->json($payload);
}
Public properties: html, message, title, redirect (all ?string), reload (bool, default false). Properties with null value are omitted from JSON output. with(key, value) stores values nested under a data key in JSON output via fluent chaining.
Modules
Extend Ergo\Module\Module. Register routes and event listeners in the constructor.
class BlogModule extends Module
{
public static function internalName(): string { return 'blog'; }
public function __construct(ApplicationInterface $application)
{
parent::__construct($application);
$app = $this->application;
$this->application->registerRoute(
'/blog',
static fn() => $app->getInstance(BlogController::class)->renderList(),
'blog_list'
);
}
public function inlineContent(string $parameter): string
{
return match($parameter) {
'latest' => $this->renderLatestPost(),
default => parent::inlineContent($parameter),
};
}
}
Register with $application->registerModule(BlogModule::class).
Use template tags [%MOD_blog%] or [%MOD_blog#latest%] to embed module output in page templates.
Templates
PageComposer assembles a full HTML page. The page template file must contain both [%MAIN_OUTPUT%] and [%HEADER_OUTPUT%] placeholders.
$page = new PageComposer($this->application);
$page->pageTemplate($this->application->template('main.htm'));
$page->title('Page title');
$page->metaDescription('Description for search engines');
$page->canonical($this->application->getUrl('homepage'));
return $this->html($page->render($mainContent));
Application::template() resolves the template path in this order (first existing file wins):
<templates>/<module>/<subdir>/<explicit language>/<file><templates>/<module>/<subdir>/<current language>/<file><templates>/<module>/<subdir>/<default language>/<file><templates>/<module>/<subdir>/<file>
I18n
Translation files live in app/lang/<language>/ as .txt files with token;value lines. Lines starting with # are comments.
# app/lang/en/messages.txt
WELCOME_TITLE;Welcome
NAV_HOME;Home
Placeholders in HTML/JSON responses use {%TOKEN%} syntax and are replaced automatically by Application::run().
In code: $this->application->translate('WELCOME_TITLE').
Translator is strict by default (missing token throws RuntimeException). Pass strict: false for a fallback that returns the token itself — Application sets this based on $config->isDevelopment().
Session
$session = new Session(); // starts session if not active
$session->set('user_id', 42);
$userId = $session->get('user_id'); // int|string|bool|float|null
$session->has('user_id'); // bool
$session->remove('user_id');
$session->regenerate(); // rotate session ID (call after login)
$session->destroy(); // clear and end session
Session validates cookies before session_start() — an invalid session ID in the cookie is silently replaced with a freshly generated one.
Ergo\Email\Mailer wraps PHPMailer. PHPMailer is not a dependency of this library — add it to your own project:
composer require phpmailer/phpmailer
use Ergo\Email\Address;
use Ergo\Email\AttachmentFile;
use Ergo\Email\Mailer;
use Ergo\Email\Message;
use PHPMailer\PHPMailer\PHPMailer;
$phpMailer = new PHPMailer();
$phpMailer->isSMTP();
$phpMailer->Host = 'smtp.example.com';
$message = new Message(
sender: new Address('from@example.com', 'Sender'),
recipients: new Address('to@example.com', 'Recipient'),
subject: 'Hello',
bodyPlaintext: 'Plain text',
bodyHtml: '<p>HTML body</p>',
);
$message->addAttachment(new AttachmentFile('/path/to/file.pdf', 'file.pdf'));
(new Mailer($phpMailer))->send($message);
Events
// Define an event
class UserLoggedIn extends \ZdenekGebauer\Events\Event
{
public function __construct(public readonly int $userId) {}
}
// Register a listener (in Application constructor or Module constructor)
$this->registerEvent(UserLoggedIn::class, static function (UserLoggedIn $event): void {
// handle login
});
// Dispatch
$this->dispatchEvent(new UserLoggedIn($userId));
// Unregister a specific listener
$this->unregisterEvent(UserLoggedIn::class, $listener);
// Unregister all listeners for an event
$this->unregisterEvent(UserLoggedIn::class);
Configuration reference
| INI key | Default | Description |
|---|---|---|
root_url | http://localhost/ | Absolute URL of the web root, with trailing slash |
mode | development | development / production / testing |
timezone | system default | PHP timezone string |
export_directory | <root>/export/ | Absolute path for exported files (sitemaps, feeds, ...). Must exist and be writable, but only for projects that call dirExport() — the default is not validated on construction |
log_directory | <root>/log/ | Absolute path to log directory |
templates_directory | <root>/app/templates/ | Absolute path to templates directory |
translations_directory | <root>/app/lang/ | Absolute path to translations root |
error_email[] | — | One or more recipient addresses for error emails |
developer_ip | — | name@ip entries granting Tracy developer panel |
language | en | Default language code |
Development
The local environment is Lando (PHP 8.5) run from WSL2 (~/projekty/Ergo);
build/check-wsl.php stops it on Windows Lando or a Windows drive. Development dependencies live in
www/composer.json, the root composer.json describes the library itself.
lando install # composer install (www/)
lando tests # all suites: Unit, Integration, Acceptance
lando coverage # Unit + Integration with code coverage report
lando infection # mutation testing, 100 % MSI required (infection.json5)
lando dependency-analyser # composer.json against the packages and extensions the code uses
lando ecs # coding standards (PSR-12), lando ecs-fix to fix
lando rector # dry-run code modernization, lando rector-fix to apply
lando phpstan # static analysis, level max with strict and deprecation rules
The Acceptance suite needs the running web server (https://www.ergo.cz.local/), so CI runs only
Unit and Integration, on PHP 8.4 and 8.5. Changes are listed in CHANGELOG.md.
Onboarding a project built on Ergo
CLAUDE.md in this repository is a condensed reference to the whole framework — component map,
request lifecycle, module system, config conventions, code style and testing rules. It is written
to be read top to bottom in a few minutes.
Use it when a new developer joins a project built on Ergo, or as context for an AI assistant
working on such a project: copy the ## Architecture, ## Code Style Requirements and ## Testing
sections into the downstream project's own instructions file. The downstream project only needs to
add what is specific to it — its modules, routes and any classes extending Application, Config
or Controller.
License
MIT — see LICENSE.