Verified against Semitexa Ultimate 2026.10.03.1952

Adding Pages and Routes

Put new routes in modules — src/modules/<Module>/ in a project, or a package under packages/ or vendor/semitexa/.

This is a convention, not a mechanical limit. ClassDiscovery merges every PSR-4 directory under src/, tests/, packages/ and vendor/semitexa/, so a payload dropped straight into src/ with an access attribute will be discovered and will answer requests. The reason to use a module anyway is that everything defining a route then lives in one predictable layout with a clear namespace, which is what the graph, the generators and the structure validator all read. A route class sitting loose in src/ works and is invisible to all of them.

If you are looking for where the boundary actually is: it is the discovery roots above. Nothing outside them is scanned.


Step-by-step: create a module and add a route

The starter Hello module (src/modules/Hello/) in a new project is a complete working example to compare against.

  1. Create the module

    bin/semitexa make:module --name=Website --target=custom --write
    

    This creates src/modules/Website/src/Application/..., src/modules/Website/src/Domain/... and src/modules/Website/tests/. You can also create the directories by hand.

  2. Know how it is loaded

    At boot, LocalModuleAutoloadRegistrar maps App\Modules\Website\ to src/modules/Website/src/ for every directory under src/modules/. There is no composer dump-autoload step and no root composer.json change. A module composer.json is optional; if you add one, use the same mapping:

    {
        "name": "app/module-website",
        "type": "semitexa-module",
        "autoload": {
            "psr-4": {
                "App\\Modules\\Website\\": "src/"
            }
        }
    }
    
  3. Create the Payload, Resource and Handler

    HTTP request DTOs go in src/Application/Payload/Request/, response DTOs in src/Application/Resource/Response/, handlers in src/Application/Handler/PayloadHandler/. See module structure for the full layout.

    This example is a JSON endpoint, GET /status.

    src/modules/Website/src/Application/Payload/Request/StatusPayload.php:

    <?php
    
    declare(strict_types=1);
    
    namespace App\Modules\Website\Application\Payload\Request;
    
    use App\Modules\Website\Application\Resource\Response\StatusResource;
    use Semitexa\Core\Attribute\AsPublicPayload;
    
    #[AsPublicPayload(path: '/status', methods: ['GET'], responseWith: StatusResource::class)]
    final class StatusPayload
    {
    }
    

    src/modules/Website/src/Application/Resource/Response/StatusResource.php:

    <?php
    
    declare(strict_types=1);
    
    namespace App\Modules\Website\Application\Resource\Response;
    
    use Semitexa\Core\Attribute\AsResource;
    use Semitexa\Core\Contract\ResourceInterface;
    use Semitexa\Core\Http\Response\ResourceResponse;
    use Semitexa\Core\Http\Response\ResponseFormat;
    
    #[AsResource(format: ResponseFormat::Json)]
    final class StatusResource extends ResourceResponse implements ResourceInterface
    {
        public function withMessage(string $message): self
        {
            $this->setRenderContext(['message' => $message]);
    
            return $this;
        }
    }
    

    src/modules/Website/src/Application/Handler/PayloadHandler/StatusHandler.php:

    <?php
    
    declare(strict_types=1);
    
    namespace App\Modules\Website\Application\Handler\PayloadHandler;
    
    use App\Modules\Website\Application\Payload\Request\StatusPayload;
    use App\Modules\Website\Application\Resource\Response\StatusResource;
    use Semitexa\Core\Attribute\AsPayloadHandler;
    use Semitexa\Core\Contract\TypedHandlerInterface;
    
    #[AsPayloadHandler(payload: StatusPayload::class, resource: StatusResource::class)]
    final class StatusHandler implements TypedHandlerInterface
    {
        public function handle(StatusPayload $payload, StatusResource $resource): StatusResource
        {
            return $resource->withMessage('Hello from the Website module');
        }
    }
    

    GET /status answers {"message":"Hello from the Website module"}. The payload is a plain class; the handler implements TypedHandlerInterface and takes the concrete payload and resource types.

    #[AsPublicPayload] makes a route anonymous. #[AsProtectedPayload] (signed-in user) and #[AsServicePayload] (machine credential) live in Semitexa\Authorization\Attribute\. A payload with none of the three is never routed.

  4. Restart the server

    bin/semitexa server:restart
    

    Swoole workers keep discovered classes and compiled templates for their lifetime, so a new route appears only after a restart. bin/semitexa routes:list confirms it. Do not treat bin/semitexa registry:sync as a required manual step for ordinary payload changes.


Responses: JSON and HTML pages

The example above returns JSON through a resource DTO marked #[AsResource(format: ResponseFormat::Json)]; its render context becomes the JSON body. For HTML pages the renderer is semitexa/ssr, which ships with the framework. Do not implement your own Twig renderer in the project.

Steps for HTML pages:

  1. Create a resource that extends Semitexa\Ssr\Application\Service\Http\Response\HtmlResponse and carries #[AsResource(handle: '...', template: '@project-layouts-<Module>/pages/thing.html.twig')].
  2. Store templates in the module under src/Application/View/templates/; they are addressed through the Twig namespace @project-layouts-<Module>, not a filesystem path.
  3. The handler fills the resource through typed with*() methods and returns it; the framework renders the template.

bin/semitexa make:page --module=Website --name=Minimal --path=/minimal --method=GET --access=public --write generates all four files in one step; its template extends the bundled theme's @project-layouts-theme-base/layouts/one-column.html.twig and puts the content in {% block main %}. The Hello module's HelloResource is a working example (template: '@project-layouts-Hello/hello.html.twig').

Detailed docs: rendering philosophy, resource DTOs and slots. Do not put raw HTML in the handler and do not create a custom renderer — return a resource DTO.

If you need the public URL shape to be editable per environment without changing PHP code, see env route override. #[AsPublicPayload(path: 'env::VAR::/fallback')] is the canonical pattern.


Where to put Request/Handler

Location Discovered for routes?
Modules: src/modules/{ModuleName}/src/ (namespace App\Modules\{ModuleName}\) Yes
Packages: project packages/ (Semitexa packages with composer.json) Yes
Vendor: installed packages (e.g. vendor/semitexa/...) Yes
Project src/ (namespace App\), outside a module Yes — discovered, but invisible to the graph, generators and structure validator

Place all new routes in a module (existing or new) under src/modules/, in packages/, or in an installed package. Loose classes still route, but they opt out of every tool that reads the module layout, so treat that as a mistake rather than a shortcut.


How discovery works (architecture)

  • ModuleRegistry finds modules in: src/modules/ (every directory), project packages/, and vendor/ (packages with type: semitexa-module).
  • LocalModuleAutoloadRegistrar registers the PSR-4 mapping App\Modules\<Name>\ → src/modules/<Name>/src/ for each local module at boot. (Semitexa\Modules\<Name>\ is mapped to the same directory for older code; new code uses App\Modules\.)
  • AttributeDiscovery reads the attributes of every class in the PSR-4 directories merged by ClassDiscovery: src/ (including the project App\ namespace), tests/, packages/, and vendor/semitexa/. Module namespaces are the convention, not the filter.

Custom 404 page (error.404 route)

If no route matches the request, or a handler throws Semitexa\Core\Http\Exception\NotFoundException, the system looks for a named route error.404 (RoutePhase::ROUTE_NAME_404; the older Application::ROUTE_NAME_404 is deprecated). If it exists, that route’s handlers run against the same request, so a module can render a custom 404 page. semitexa/ssr already ships one — route index error.404, payload DefaultNotFoundPagePayload.

  • Register a Payload with name: 'error.404' and path/methods as needed (e.g. path '/404', methods ['GET']), plus a Response class and handler that render your 404 view.
  • Throw Semitexa\Core\Http\Exception\NotFoundException in any handler when a resource is missing; the framework will then dispatch to the error.404 route if registered, or return a plain 404 response.

Sign-in page for guests on protected pages (error.401 route)

A page a guest must not see is #[AsProtectedPayload]: the auth gate refuses the guest before the page's handler runs. When that refusal reaches a browser (an HTML request), the framework looks for a named route error.401 (RoutePhase::ROUTE_NAME_401) and runs it the way it runs error.404. Register one in the module that owns sign-in and render the sign-in form there. The response keeps status 401. Without the route the built-in 401 page is served. The error.401 mapping and ErrorPageContext::$returnTo arrive with the first semitexa/core release tagged after 2026.11.05.1529; an older core serves the built-in page even when the route exists.

The pieces, in the module that owns sign-in:

  • The page: a Payload with name: 'error.401', marked #[AsPublicPayload] (a guest has to be able to see it), plus a Response and handler that render the form. Its handler reads where the guest was going from ErrorPageContextStore::current()?->returnTo ?? '/' (Semitexa\Core\Error\ErrorPageContextStore). The context exists only while the framework is answering a refusal; a guest who opens the sign-in page directly has none, and the fallback keeps the page rendering.
  • The form posts to a sign-in endpoint of its own, a separate #[AsPublicPayload] route such as POST /sign-in, never to the page the guest asked for. A form with no action posts back to /account, which is protected and refuses the guest again. Put returnTo in a hidden field.
  • The sign-in payload guards the destination in its setter, as payload setters own every value that comes in: $this->returnTo = RedirectTarget::localPath($value); (Semitexa\Core\Http\RedirectTarget). The handler then, after a successful sign-in, redirects with setRedirect($payload->getReturnTo()) and never sees an unchecked value. The field comes back from the browser, so anyone can post their own; localPath() keeps it only when it is a path on this site and gives / otherwise: a scheme or host, //evil.com, /\evil.com, a tab or line break inside the path. The check setRedirect() itself applies is not enough here: it lets a handler's own redirect go to this site's other hosts, localhost and the sign-in providers, so https://github.com/... passes it. Do not write a Location header yourself or check the value with a rule of your own: a "starts with a single /" test lets /\evil.com through.
  • Why returnTo and not requestPath: returnTo is the address as the guest asked for it, the served path with a locale prefix kept (/uk/account) and the query string (/checkout?cart=123). requestPath is the routed path: under LOCALE_URL_PREFIX=true the prefix is gone, so a return there opens the page in the default language, and the query is never in it.
  • Who gets the page: a request answered in HTML. A client sending Accept: */* gets the format the route lists first in produces, so on a protected route that lists HTML first an API client sending */* receives the sign-in page (status 401) rather than the JSON body. Send Accept: application/json when you need the JSON refusal.
  • Do not make a page public and branch on "is there a user" in its handler or template to greet guests. That page is open to anyone; keep it protected and let error.401 do the greeting.

Common mistakes / FAQ

My payload in src/ routes, but no tooling sees it.
That is expected. src/ is scanned, so the route works, but the module-structure validator, the project graph and the generators all key off the module layout. Move the class into src/modules/{Module}/src/Application/... under the App\Modules\{Module}\ namespace and it rejoins them.

I added a new Payload and Handler but the route doesn't exist (404)?
Check that the class is under src/modules/<Module>/src/, that its namespace starts with App\Modules\<Module>\ and matches the directory, and that you ran bin/semitexa server:restart. registry:sync is a maintenance command, not the default fix for ordinary payload changes.

Can I patch AttributeDiscovery to widen discovery?
Do not patch vendor. The discovery roots (src/, tests/, packages/, vendor/semitexa/) already cover every location a Semitexa project is expected to use.

Summary

  • New pages and routes belong in modules (src/modules/, packages/, or vendor/semitexa/) — not because loose classes fail to route, but because they drop out of every tool that reads the module layout.
  • A local module is src/modules/<Module>/src/Application/... under App\Modules\<Module>\, mapped at boot by LocalModuleAutoloadRegistrar; no composer dump-autoload.
  • Payloads are plain classes with an access attribute; handlers implement TypedHandlerInterface; responses are resource DTOs.
  • After adding or changing Payloads: bin/semitexa server:restart. Use registry:sync only for maintenance flows explicitly documented by a package.
Have a product idea?One free MVP every month