### Local Development Setup
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/5-extra-topics/04-contributing.md
Commands to set up the Tempest framework locally after forking and cloning the repository. Ensure you have PHP, Composer, and Bun installed.
```shell
cd /path/to/your/clone
composer update
bun install
bun dev
```
--------------------------------
### Example Deployment Script
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/5-extra-topics/03-deployments.md
This bash script outlines the steps for deploying a Tempest project, including dependency installation, cache clearing, migrations, and asset compilation.
```bash
#!/bin/bash
# Sourcing bashrc because we're connecting via SSH
. /home/user/.bashrc
# Dependencies:
composer install --no-dev
bun install
# Tempest:
tempest cache:clear --force --internal --all
tempest discovery:generate
tempest migrate:up --force
tempest static:clean --force
bun run build
tempest static:generate --allow-dead-links --verbose=true
```
--------------------------------
### Run the Framework Installer
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/0-getting-started/02-installation.md
After installing Tempest as a package, use this command to install framework entry points and configuration files into your project. You can select which files to install.
```txt
./vendor/bin/tempest install framework
```
--------------------------------
### Install Vite and Tailwind CSS Scaffolding
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/0-getting-started/02-installation.md
Optionally install a basic front-end setup including Vite and Tailwind CSS by running this command and following the wizard.
```sh
php tempest install vite --tailwind
```
--------------------------------
### Implement a File Installer
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/5-extra-topics/01-package-development.md
Create a custom installer by implementing the Installer interface and using the PublishesFiles trait. This allows you to publish files to a user's project and automatically adjust their imports.
```php
use Tempest\Core\Installer;
use Tempest\Core\PublishesFiles;
use Tempest\Discovery\SkipDiscovery;
use Tempest\Generation\ClassManipulator;
use function Tempest\src_namespace;
use function Tempest\src_path;
final readonly class AuthInstaller implements Installer
{
use PublishesFiles;
private(set) string $name = 'auth';
public function install(): void
{
$publishFiles = [
__DIR__ . '/User.php' => src_path('User.php'),
__DIR__ . '/UserMigration.php' => src_path('UserMigration.php'),
__DIR__ . '/Permission.php' => src_path('Permission.php'),
__DIR__ . '/PermissionMigration.php' => src_path('PermissionMigration.php'),
__DIR__ . '/UserPermission.php' => src_path('UserPermission.php'),
__DIR__ . '/UserPermissionMigration.php' => src_path('UserPermissionMigration.php'),
];
foreach ($publishFiles as $source => $destination) {
$this->publish(
source: $source,
destination: $destination,
);
}
$this->publishImports();
}
}
```
--------------------------------
### Install OAuth with Tempest Installer
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/17-oauth.md
Use the Tempest installer to quickly set up OAuth in your project. This command prompts for provider selection, publishes configuration files, and optionally adds credentials and dependencies.
```sh
./tempest install auth --oauth
```
--------------------------------
### Install Console Command Completions
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/04-console-commands.md
Install shell completions for Zsh, Bash, and Fish by running the `install` command or directly executing `completion:install`. This sets up autocompletion for command names and options.
```console
./tempest install
```
```console
./tempest completion:install
```
--------------------------------
### Setup Database for Tests
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/07-testing.md
Extend IntegrationTest and use the `setup()` method on the `database` utility within a `#[PreCondition]` method to prepare the database for testing.
```php
final class ShowAircraftControllerTest extends IntegrationTest
{
#[PreCondition]
protected function configure(): void
{
$this->database->setup();
}
}
```
--------------------------------
### Mocking Asynchronous Process Results
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/16-process.md
Use `describe()` to define expectations for commands, including output, exit codes, and the number of times the `running` property should be true. This example mocks 'composer up' and 'bun install'.
```php
$this->process->mockProcessResults([
'composer up' => $this->process
->describe()
->iterations(1)
->output('Nothing to install, update or remove'),
'bun install' => $this->process
->describe()
->iterations(4)
->output('Checked 225 installs across 274 packages (no changes) [144.00ms]')
]);
$this->process->assertCommandRan('composer up', function (ProcessResult $result) {
$this->assertSame("Nothing to install, update or remove\n", $result->output);
});
```
--------------------------------
### Start Asynchronous Process with Live Output
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/16-process.md
Use the `start` method to run a process asynchronously and `wait` with a callback to capture live output.
```php
$this->executor
->start('composer update')
->wait(function (OutputChannel $channel, string $output) {
echo $output;
});
```
--------------------------------
### Install Responsive Images Package
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/3-packages/03-responsive-image.md
Install the responsive image package using Composer.
```bash
composer require tempest/responsive-image
```
--------------------------------
### Install tempest/event-bus
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/5-extra-topics/02-standalone-components.md
Use composer to install the tempest/event-bus package.
```bash
composer require tempest/event-bus
```
--------------------------------
### Install tempest/http
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/5-extra-topics/02-standalone-components.md
Use composer to install the tempest/http package.
```bash
composer require tempest/http
```
--------------------------------
### Initialize Tempest View Renderer (Standalone)
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/02-views.md
Use Tempest View as a standalone engine by requiring 'tempest/view' and creating a TempestViewRenderer instance. This example shows the minimal setup without view components.
```php
use Tempest\View\Renderers\TempestViewRenderer;
use function Tempest\View\view;
$renderer = TempestViewRenderer::make();
$html = $renderer->render(view('home.view.php', name: 'Brent'));
```
--------------------------------
### Install Tempest Highlight Package
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/3-packages/01-highlight.md
Install the Tempest Highlight package using Composer.
```console
composer require tempest/highlight
```
--------------------------------
### Install tempest/container
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/5-extra-topics/02-standalone-components.md
Use composer to install the tempest/container package.
```bash
composer require tempest/container
```
--------------------------------
### Welcome Text View Example
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/07-mail.md
Example of a view file for rendering plain text email content. It uses variables passed from the email class.
```html
Hello {{ $user->name }}
Please visit this link to activate your account: {{ $user->activationLink }}.
See you soon!
Tempest
```
--------------------------------
### Install tempest/command-bus
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/5-extra-topics/02-standalone-components.md
Use composer to install the tempest/command-bus package.
```bash
composer require tempest/command-bus
```
--------------------------------
### Install Read-Only Storage Adapter
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/05-file-storage.md
Install the `league/flysystem-read-only` adapter using Composer. This is a prerequisite for configuring a read-only storage.
```sh
composer require league/flysystem-read-only
```
--------------------------------
### Basic Responsive Image Factory Setup
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/3-packages/03-responsive-image.md
Configure and create a ResponsiveImageFactory instance. Ensure the srcPath and publicPath are correctly set.
```php
use Tempest\ResponsiveImage\ResponsiveImageFactory;
use Tempest\ResponsiveImage\ResponsiveImageConfig;
$config = new ResponsiveImageConfig(
srcPath: __DIR__ . '/path/to/image/sources',
publicPath: __DIR__ . '/../public',
);
$imageFactory = new ResponsiveImageFactory($config);
$image = $imageFactory->create('/parrot.jpg');
echo $image->html;
```
--------------------------------
### Install Tempest Framework
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/README.md
Command to install the Tempest framework into an existing PHP project using Composer.
```bash
composer require tempest/framework
```
--------------------------------
### Install tempest/mapper
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/5-extra-topics/02-standalone-components.md
Use composer to install the tempest/mapper package.
```bash
composer require tempest/mapper
```
--------------------------------
### Gutter Rendering with Start Line
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/3-packages/01-highlight.md
Enable gutter rendering with a specified starting line number.
```php
$highlighter = new Highlighter()->withGutter(startAt: 10);
```
--------------------------------
### Install Tempest Markdown
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/3-packages/04-markdown.md
Install the tempest/markdown package using Composer.
```bash
composer require tempest/markdown
```
--------------------------------
### Installing view components
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/02-views.md
Command to install vendor-provided view components into your local project. Allows selection of components like `x-csrf-token`, `x-markdown`, etc.
```console
./tempest install view-components
│ Select which view components you want to install
│ / Filter...
│ → ⋅ x-csrf-token
│ ⋅ x-markdown
│ ⋅ x-input
│ ⋅ x-icon
…
```
--------------------------------
### Run the Front-End Development Server
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/0-getting-started/02-installation.md
After installing front-end assets, use this command to serve them on-the-fly using npm.
```bash
npm run dev
```
--------------------------------
### Install Tempest Console Package
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/3-packages/02-console.md
Install the tempest/console package using Composer.
```sh
composer require tempest/console
```
--------------------------------
### Install tempest/debug
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/5-extra-topics/02-standalone-components.md
Use composer to install the tempest/debug package.
```bash
composer require tempest/debug
```
--------------------------------
### Install Authentication Package
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/04-authentication.md
Use this command to install the authentication package for your Tempest application.
```sh
./tempest install auth
```
--------------------------------
### Migration Command Example
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/README.md
Illustrates a console command for running database migrations. It includes middleware for safety and event handling for migration completion.
```php
final class MigrateUpCommand
{
public function __construct(
private Console $console,
private MigrationManager $migrationManager,
) {}
#[ConsoleCommand(
name: 'migrate:up',
description: 'Run all new migrations',
middleware: [ForceMiddleware::class, CautionMiddleware::class],
)]
public function __invoke(): void
{
$this->migrationManager->up();
$this->console->success("Everything migrated");
}
#[EventHandler]
public function onMigrationMigrated(MigrationMigrated $migrationMigrated): void
{
$this->console->writeln("- {$migrationMigrated->name}");
}
}
```
--------------------------------
### Install Session Support
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/01-routing.md
Installs session support, including publishing necessary configuration files and migrations for database or Redis sessions.
```sh
./tempest install sessions
```
--------------------------------
### Install CommonMark Package
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/3-packages/01-highlight.md
This command installs the `league/commonmark` package, which is a prerequisite for enabling Markdown support in Tempest Highlight.
```bash
composer require league/commonmark;
```
--------------------------------
### View Component Metadata Example
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/4-internals/02-view-spec.md
An example of the JSON output from the 'meta:view-component' command, detailing the 'x-markdown' component's file, name, slots, and variables.
```json
{
"file": "/…/tempest-framework/packages/view/src/Components/x-markdown.view.php",
"name": "x-markdown",
"slots": [],
"variables": [
{
"type": "string|null",
"name": "$content",
"attributeName": "content",
"description": "The markdown content from a variable"
}
]
}
```
--------------------------------
### Install Vite Integration
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/02-asset-bundling.md
Run this command to install Vite and its related configurations into your Tempest project. It sets up the Vite plugin, configuration file, and entrypoints.
```sh
php tempest install vite
```
--------------------------------
### Install Ellison Package
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/3-packages/01-highlight.md
Install the Ellison PHP package using Composer. This command adds the necessary library to your project.
```bash
composer require assertchris/ellison
```
--------------------------------
### Configure Redis Cache
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/06-cache.md
Example of configuring Redis as the cache back-end by creating a cache configuration file.
```php
return new RedisCacheConfig(
host: env('REDIS_HOST', default: '127.0.0.1'),
port: env('REDIS_PORT', default: 6379),
username: env('REDIS_USERNAME'),
password: env('REDIS_PASSWORD'),
);
```
--------------------------------
### Installing Symfony Postmark Mailer Dependencies
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/07-mail.md
Install the necessary Symfony mailer dependencies for Postmark integration.
```bash
composer require symfony/postmark-mailer
composer require symfony/http-client
```
--------------------------------
### Example Responsive Image HTML Output
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/3-packages/03-responsive-image.md
This is an example of the HTML output generated for a responsive image, including srcset attribute.
```html
```
--------------------------------
### Serve a Tempest Application with PHP's Built-in Server
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/0-getting-started/02-installation.md
If you do not have a dedicated development environment, use this command to start PHP's built-in server for local development.
```sh
php tempest serve
# PHP 8.5.1 Development Server (http://localhost:8000) started:
```
--------------------------------
### Production Environment Variables
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/5-extra-topics/03-deployments.md
Example .env file configuration for a production environment, including signing key, environment settings, base URI, and cache configurations.
```dotenv
# Generated by `tempest key:generate`
SIGNING_KEY=…
# Set to production
ENVIRONMENT=production
# Set the base URI to your production domain
BASE_URI=https://tempestphp.com
# Enable all caches
INTERNAL_CACHES=true
# Use full discovery cache in production
DISCOVERY_CACHE=true
# Set the PHP executable path if you're using Tempest's front-end scaffolding
# See: https://tempestphp.com/2.x/getting-started/installation#scaffolding-front-end-assets
PHP_EXECUTABLE_PATH=/usr/bin/php8.4
# Any project-specific environment variables you may need.
# …
```
--------------------------------
### Define a Command Object
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/10-command-bus.md
Commands are simple data classes. This example shows a `CreateUser` command with properties for user details.
```php
final readonly class CreateUser
{
public function __construct(
public string $name,
public string $email,
public string $passwordHash,
) {}
}
```
--------------------------------
### Create and Acquire Lock
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/06-cache.md
Example of creating a cache lock, acquiring it, performing an action, and releasing it.
```php
// Create the lock
$lock = $cache->lock('processing', Duration::seconds(30));
// Acquire the lock, do something and release it.
if ($lock->acquire()) {
$this->process();
$lock->release();
}
// Or using a callback, with an optional wait
// time if the lock is not yet available.
$lock->execute($this->process(...), wait: Duration::seconds(30));
```
--------------------------------
### Retrieve Tagged Singleton Directly from Container
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/05-container.md
When you have a container instance, you can directly retrieve a specific tagged singleton using the 'tag' argument in the get method, for example, to get a CLI-configured Highlighter.
```php
$container->get(Highlighter::class, tag: 'cli');
```
--------------------------------
### Testing a GET Request in Tempest
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/01-routing.md
Demonstrates how to test a GET request to the '/account/profile' route using the http testing utility. Asserts that the response is OK and contains specific text.
```PHP
final class ProfileControllerTest extends IntegrationTestCase
{
public function test_can_render_profile(): void
{
$response = $this->http
->get('/account/profile')
->assertOk()
->assertSee('My Profile');
}
}
```
--------------------------------
### Cache Interface Methods
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/06-cache.md
Demonstrates common methods of the Cache interface: get, put, and resolve.
```php
/**
* Gets a value from the cache by the given key.
*/
$cache->get($key);
/**
* Sets a value in the cache for the given key.
*/
$cache->put($key, $value);
/**
* Gets a value from the cache by the given key, or resolve it using the given callback.
*/
$cache->resolve($key, function () {
return $this->expensiveOperation();
});
```
--------------------------------
### Define a GET route with an optional parameter and regex constraint
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/01-routing.md
Optional parameters can also have regular expression constraints. This example matches URIs with or without a numeric ID.
```php
#[Get(uri: '/aircraft/{?id:\d+}')]
public function show(?int $id): View
{
// Matches /aircraft and /aircraft/123 (numeric only)
}
```
--------------------------------
### Ellison Language Example
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/3-packages/01-highlight.md
This demonstrates how to use the 'ellison' language highlighting, typically within a preformatted text block.
```ellison
Hello world!
```
--------------------------------
### Returning Views from Controllers
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/4-internals/02-view-spec.md
Examples of returning view files from controllers, passing data via named arguments. Supports absolute, relative, and discovery paths.
```php
return view(__DIR__ . '/views/home.view.php', title: 'foo', description: 'bar');
return view('./views/home.view.php', title: 'foo', description: 'bar');
return view('views/home.view.php', title: 'foo', description: 'bar');
```
--------------------------------
### Define a Static Page Controller Action
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/13-static-pages.md
Tag a controller action with #[StaticPage] and #[Get] to mark it for static page generation. This example shows a basic front page controller.
```php
use Tempest\Router\Get;
use Tempest\Router\StaticPage;
use Tempest\View\View;
use function Tempest\View\view;
final readonly class FrontPageController
{
#[StaticPage]
#[Get('/')]
public function frontpage(): View
{
return view('./front-page');
}
}
```
--------------------------------
### Production Storage Configuration
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/06-configuration.md
Example of a production-specific storage configuration using S3. It references environment variables for credentials and bucket details.
```php
return new S3StorageConfig(
bucket: env('S3_BUCKET'),
region: env('S3_REGION'),
accessKeyId: env('S3_ACCESS_KEY_ID'),
secretAccessKey: env('S3_SECRET_ACCESS_KEY')
);
```
--------------------------------
### Conventional Commit Example
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/5-extra-topics/04-contributing.md
Illustrates the conventional commit format for commit messages, including type, scope, and description. Use imperative mood and lowercase for descriptions.
```diff
```diff
- feat(support): Adds some cool feature
+ feat(support): add some cool feature
```
```
--------------------------------
### Configure Custom Discovery Locations
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/3-packages/02-console.md
Provide additional discovery locations to the ConsoleApplication::boot() method for fine-grained control over command discovery. This example specifies a namespace and path for custom commands.
```php
use Tempest\Console\ConsoleApplication;
use Tempest\Discovery\DiscoveryLocation;
ConsoleApplication::boot(
discoveryLocations: [
new DiscoveryLocation(
namespace: 'MyApp\',
path: __DIR__ . '/src',
),
],
)->run();
```
--------------------------------
### Fake OAuth Client Setup
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/17-oauth.md
Replace the OAuth client implementation with a fake one for testing. This method returns the fake client instance and allows for assertion methods.
```php
$oauth = $this->oauth->fake(new OAuthUser(
id: 'jon',
email: 'jondoe@example.test',
nickname: 'jondoe',
));
```
--------------------------------
### Implement a Data Provider
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/13-static-pages.md
Implement the DataProvider interface to yield controller action parameters for each static page to be generated. This example provides category and slug for documentation chapters.
```php
use Tempest\Router\DataProvider;
final readonly class ChapterDataProvider implements DataProvider
{
public function __construct(
private ChapterRepository $chapters
) {}
public function provide(): Generator
{
foreach ($this->chapters->all() as $chapter) {
// Yield an array of parameters that should be passed to the controller action,
yield [
'category' => $chapter->category,
'slug' => $chapter->slug,
];
}
}
}
```
--------------------------------
### Manually create index.php for HttpApplication
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/5-extra-topics/02-standalone-components.md
Manually create an index.php file to boot the HttpApplication. Ensure the 'root' path points to your project's root folder.
```php
run();
```
--------------------------------
### Implement Response Processor
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/01-routing.md
Create a ResponseProcessor to perform actions on a response before it's sent. This example displays a custom error page for unsuccessful responses.
```php
use function Tempest\View\view;
final readonly class ErrorResponseProcessor implements ResponseProcessor
{
public function process(Response $response): Response
{
if (! $response->status->isSuccessful()) {
return $response->setBody(view('./error.view.php', status: $response->status));
}
return $response;
}
}
```
--------------------------------
### Manually boot ConsoleApplication
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/5-extra-topics/02-standalone-components.md
Manually boot the console application using the ConsoleApplication::boot() method.
```php
run();
```
--------------------------------
### Responsive Image HTML with Custom Attributes
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/3-packages/03-responsive-image.md
Example of the final HTML output for a responsive image, including custom alt text, sizes, and lazy loading attributes.
```html
```
--------------------------------
### Boot a Console Application
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/3-packages/02-console.md
Basic structure for booting a console application using Tempest. Ensure the autoloader is included and the ConsoleApplication is booted and run.
```php
{:hl-comment:#!/usr/bin/env php:}
run();
```
--------------------------------
### Installing Symfony Mailgun Mailer Dependency
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/07-mail.md
Install the Symfony mailer dependency for Mailgun integration.
```bash
composer require symfony/mailgun-mailer
```
--------------------------------
### Book Controller Example
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/README.md
Demonstrates a controller for handling book-related requests, including showing a specific book and storing a new one. Uses attributes for routing and mapping requests to domain objects.
```php
final class BookController
{
#[Get('/books/{book}')]
public function show(Book $book): Response
{
return new Ok($book);
}
#[Post('/books')]
public function store(CreateBookRequest $request): Response
{
$book = map($request)->to(Book::class)->save();
return new Redirect([self::class, 'show'], book: $book->id);
}
// …
}
```
--------------------------------
### View Path Examples
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/02-views.md
Illustrates different ways to specify the path to a view file when using the `view` function. Paths can be absolute, relative to the current directory, or relative to the configured view directory.
```php
return view(__DIR__ . '/views/home.view.php');
```
```php
return view('./views/home.view.php');
```
```php
return view('views/home.view.php');
```
--------------------------------
### Use GenericContainer with initializers
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/5-extra-topics/02-standalone-components.md
Instantiate a GenericContainer, add initializers, and retrieve a service.
```php
$container = new Tempest\Container\GenericContainer();
$container->addInitializer(FooInitializer::class);
$foo = $container->get(Foo::class);
```
--------------------------------
### Install Twig Engine
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/02-views.md
Install the Twig templating engine using Composer. This is a prerequisite for using Twig with Tempest.
```sh
composer require twig/twig
```
--------------------------------
### Overriding Configuration Instance
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/06-configuration.md
Illustrates how to completely replace a configuration singleton with a new instance, such as setting a specific path for SQLite.
```php
$this->container->config(new SQLiteConfig(
path: root_path('database.sqlite'),
));
```
--------------------------------
### PHP Controller with GET Route
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/packages/generation/tests/Php/__snapshots__/ClassManipulatorTest__transforms_functions__1.txt
Defines a controller that responds to GET requests on a specific URI and renders a view.
```php
addLanguage(new TempestViewLanguage())
->addLanguage(new TempestConsoleWebLanguage())
->addLanguage(new ExtendedJsonLanguage());
$environment
->addExtension(new CommonMarkCoreExtension())
->addExtension(new FrontMatterExtension())
->addRenderer(FencedCode::class, new CodeBlockRenderer($highlighter))
->addRenderer(Code::class, new InlineCodeBlockRenderer($highlighter));
return new MarkdownConverter($environment);
}
}
```
--------------------------------
### Install Blade Engine Bridge
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/02-views.md
Install the Tempest bridge for the Blade templating engine using Composer. This package facilitates the integration of Blade with Tempest.
```sh
composer require tempest/blade
```
--------------------------------
### Registering Dynamic Database Connections with Middleware
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/03-database.md
Register dynamic database connections within application entry points, such as using middleware. This example demonstrates a middleware that resolves the tenant ID and connects the corresponding database.
```php
use Tempest\Container\Container;
use Tempest\Router\HttpMiddleware;
use Tempest\Support\Priority;
#[Priority(Priority::HIGHEST)]
final class ConnectTenantMiddleware implements HttpMiddleware
{
public function __construct(
private Container $container,
) {}
public function __invoke(Request $request, HttpMiddlewareCallable $next): Response
{
$tenantId = // Tenant ID resolution from request
(new ConnectTenant)($tenantId);
return $next($request);
}
}
```
--------------------------------
### Commit Scope Examples
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/5-extra-topics/04-contributing.md
Provides examples of common commit scopes used in Tempest. Scopes help categorize changes for better organization and readability.
```text
```
{:hl-property:feat:}({:hl-keyword:support:}): add `StringHelper` class
{:hl-property:feat:}({:hl-keyword:support/string:}): add `uuid` method
{:hl-property:perf:}({:hl-keyword:discovery:}): improve cache efficiency
{:hl-property:refactor:}({:hl-keyword:highlight:}): improve code readability
{:hl-property:docs:}: mention new `highlight` package
{:hl-property:chore:}: update dependencies
{:hl-property:style:}: apply php-cs-fixer
```
```
--------------------------------
### Retrieving Request Data with get()
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/01-routing.md
Use the Request's get method to retrieve values from the request body or query parameters. Other methods like hasBody and hasQuery are also available.
```php
use Tempest\Router\Get;
use Tempest\Http\Request;
final readonly class AircraftController
{
#[Get(uri: '/aircraft')]
public function me(Request $request): View
{
$icao = $request->get('icao');
// …
}
}
```
--------------------------------
### Define an Entrypoint Script
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/02-asset-bundling.md
Create an entrypoint file (e.g., `main.entrypoint.ts`) to serve as the starting point for your application's assets. Tempest automatically discovers files with the `.entrypoint.{ts,js,css}` extension.
```js
console.log('Hello, world! 🌊')
```
--------------------------------
### Get First Element and Process Array with ImmutableArray
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/08-primitive-utilities.md
Shows how to use the functional API to get the first element of a collection and the object-oriented API to reverse and map an array of file paths, potentially transforming them into BlogPost objects.
```php
use Tempest\Support\Arr;
use Tempest\Support\Arr\ImmutableArray;
// Functional API
$first = Arr\first($collection);
// Object-oriented API
$items = new ImmutableArray(glob(__DIR__ . '/content/*.md'))
->reverse()
->map(function (string $path) {
// …
})
->mapTo(BlogPost::class);
```
--------------------------------
### Get Current URI
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/packages/view/tests/Fixtures/html/3.html
Retrieves and displays the current URI.
```html
uri(); ?>
```
--------------------------------
### Create Tempest Project
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/README.md
Command to create a new Tempest project from scratch using Composer.
```bash
composer create-project tempest/app
```
--------------------------------
### Boot Discovery with Autoload
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/05-discovery.md
Boots the discovery process using a PSR-11 container and automatically loads discovery locations from composer.json. Ensure the container is available and the root path is correctly specified.
```php
use Tempest\Discovery\BootDiscovery;
use Tempest\Discovery\DiscoveryConfig;
new BootDiscovery(
container: $container,
config: DiscoveryConfig::autoload($rootPath),
)();
```
--------------------------------
### Multi-line Deletion Tag Example
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/3-packages/01-highlight.md
Demonstrates a multi-line deletion tag within a PHP function.
```php
```php{1}
public function before(TokenType $tokenType): string
{
$style = match ($tokenType) {
{- TokenType::KEYWORD => TerminalStyle::FG_DARK_BLUE,
TokenType::PROPERTY => TerminalStyle::FG_DARK_GREEN,
TokenType::TYPE => TerminalStyle::FG_DARK_RED,
TokenType::GENERIC => TerminalStyle::FG_DARK_CYAN,
TokenType::VALUE => TerminalStyle::FG_BLACK,
TokenType::COMMENT => TerminalStyle::FG_GRAY,
TokenType::ATTRIBUTE => TerminalStyle::RESET,-}
};
return TerminalStyle::ESC->value . $style->value;
}
```
```
--------------------------------
### Tempest View Syntax Example
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/02-views.md
Demonstrates the syntax of Tempest View, including component inheritance, data passing, loops, conditional rendering, and comments. Uses HTML attributes prefixed with colons for control flow.
```html
{{-- a comment which won't be rendered to HTML --}}
{!! $post->title !!}
{{ $post->date }}
-
```
--------------------------------
### Run Synchronous Process
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/16-process.md
Use the `run` method on `ProcessExecutor` to execute a command synchronously and get its result.
```php
use Tempest\Process\ProcessExecutor;
final readonly class Composer
{
public function __construct(
private ProcessExecutor $executor
) {}
public function update(): void
{
$this->executor->run('composer update');
}
}
```
--------------------------------
### Dispatch command using tempest/command-bus
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/5-extra-topics/02-standalone-components.md
Boot the Tempest kernel, resolve the command bus from the container, and dispatch a command. Alternatively, use the global 'command' function.
```php
$container = Tempest::boot();
// You can manually resolve the command bus from the container
$commandBus = $container->get(\Tempest\CommandBus\CommandBus::class);
$commandBus->dispatch(new MyCommand());
// Or use the `command` function, which is shipped with the package
\Tempest\command(new MyCommand());
```
--------------------------------
### Expression Attributes in HTML
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/4-internals/02-view-spec.md
Attributes starting with ':' are interpreted as PHP code. Used for control structures or data passing.
```html
```
--------------------------------
### WelcomeEmail Class Implementation
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/07-mail.md
Implement the Email interface to define custom email structures. The Envelope contains metadata like subject and recipients.
```php
use Tempest\Mail\Email;
use Tempest\Mail\Envelope;
use Tempest\View\View;
use function Tempest\View\view;
final class WelcomeEmail implements Email
{
public function __construct(
private readonly User $user,
) {}
public Envelope $envelope {
get => new Envelope(
subject: 'Welcome',
to: $this->user->email,
);
}
public string|View $html {
get => view('welcome.view.php', user: $this->user);
}
}
```
--------------------------------
### Manually Configure Entrypoints in Vite
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/02-asset-bundling.md
Opt-out of the default naming convention by manually defining entrypoints in `vite.config.php`. Paths must be relative to the project root. Ensure your base template specifies which entrypoint to include.
```php
return new ViteConfig(
entrypoints: [
'app/main.css',
'app/main.ts',
],
);
```
--------------------------------
### Registering a Package Provider Listener
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/5-extra-topics/01-package-development.md
Use this snippet to register a listener for the KernelEvent::BOOTED event. This allows you to perform package-specific setup after the Tempest kernel has booted but before application code runs. Inject any necessary dependencies into the provider's constructor.
```php
use Tempest\Core\KernelEvent;
use Tempest\EventBus\EventHandler;
final readonly class MyPackageProvider
{
public function __construct(
// You can inject any dependency you like
private Container $container,
) {}
#[EventHandler(KernelEvent::BOOTED)]
public function initialize(): void
{
// Do whatever needs to be done
$this->container->…
}
}
```
--------------------------------
### Install Pest PHP
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/07-testing.md
Use Composer to remove the PHPUnit dependency and add Pest with its dependencies. This is a prerequisite for using Pest.
```sh
composer remove phpunit/phpunit
composer require pestphp/pest --dev --with-all-dependencies
```
--------------------------------
### Injecting the Logger Interface
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/09-logging.md
To start logging messages, inject the `Tempest\Log\Logger` interface into your classes. By default, logs go to `.tempest/logs`.
```php
use Tempest\Log\Logger;
final readonly class UserService
{
public function __construct(
private Logger $logger,
) {}
}
```
--------------------------------
### Create a New Tempest Application
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/0-getting-started/02-installation.md
Use this command to scaffold a new Tempest project using the official application template. Navigate into the created directory afterward.
```sh
composer create-project tempest/app my-app
cd my-app
```
--------------------------------
### HTML with CSS Injection Example
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/3-packages/01-highlight.md
This HTML snippet demonstrates how CSS can be injected within style tags, which should be highlighted as CSS.
```html
```
--------------------------------
### Vite Entrypoint File Discovery
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/05-discovery.md
This snippet shows how to discover specific file types (e.g., .ts, .css, .js) that are marked as entrypoints. It implements both `Discovery` and `DiscoversPath` interfaces, processing files based on their path and adding them to Vite's configuration.
```php
use Tempest\Discovery\Discovery;
use Tempest\Discovery\DiscoversPath;
use Tempest\Discovery\IsDiscovery;
use Tempest\Support\Str;
final class ViteDiscovery implements Discovery, DiscoversPath
{
use IsDiscovery;
public function __construct(
private readonly ViteConfig $viteConfig,
) {}
// We are not discovering any class, so we return immediately.
public function discover(DiscoveryLocation $location, ClassReflector $class): void
{
return;
}
// This method is called for every file in registered discovery locations.
// We can use the `$path` to determine whether we are interested in it.
public function discoverPath(DiscoveryLocation $location, string $path): void
{
// We are interested in `.ts`, `.css` and `.js` files only.
if (! Str\ends_with($path, ['.ts', '.css', '.js'])) {
return;
}
// These files need to be specifically marked as `.entrypoint`.
if (! str($path)->beforeLast('.')->endsWith('.entrypoint')) {
return;
}
$this->discoveryItems->add($location, [$path]);
}
// When discovery is cached, `discover` and `discoverPath` are not called.
// Instead, `discoveryItems` is already fed with serialized data, which
// we can use. In this case, we add the paths to the Vite config.
public function apply(): void
{
foreach ($this->discoveryItems as [$path]) {
$this->viteConfig->addEntrypoint($path);
}
}
}
```
--------------------------------
### Manage Session Data
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/01-routing.md
Use the Session class to manage session data. This example toggles a 'selected_todo' item in the session.
```php
use Tempest\Http\Session\Session;
final readonly class TodoController
{
public function __construct(
private Session $session,
) {}
#[Post('/select/{todo}')]
public function select(Todo $todo): View
{
if ($this->session->get('selected_todo') === $todo->id) {
$this->session->remove('selected_todo');
} else {
$this->session->set('selected_todo', $todo->id);
}
return $this->list();
}
}
```
--------------------------------
### Create a Database Seeder
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/03-database.md
Implement the `DatabaseSeeder` interface to create custom seeders. The `run` method accepts an optional database identifier for targeted seeding.
```php
use Tempest\Database\DatabaseSeeder;
use UnitEnum;
use function Tempest\Database\query;
final class BookSeeder implements DatabaseSeeder
{
public function run(?string|UnitEnum $database): void
{
query(Book::class)
->insert(title: 'Timeline Taxi')
->onDatabase($database)
->execute();
}
}
```
--------------------------------
### Creating a Raw SQL Migration
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/03-database.md
Use raw SQL files for migrations, ensuring the file name or migration class property dictates the application order. This example shows a simple CREATE TABLE statement.
```sql
CREATE TABLE Publisher
(
`id` INTEGER,
`name` TEXT NOT NULL
);
```
--------------------------------
### Reference Generated Types in TypeScript
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/18-typescript.md
Example of how to reference globally generated types within your TypeScript code, organized by namespace.
```ts
defineProps<{
entry: Module.Changelog.ChangelogEntry
}>()
```
--------------------------------
### Basic Code Highlighting
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/3-packages/01-highlight.md
Instantiate the Highlighter and parse code with a specified language.
```php
$highlighter = new \Tempest\Highlight\Highlighter();
$code = $highlighter->parse($code, 'php');
```
--------------------------------
### Returning a View Response
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/01-routing.md
Demonstrates returning a Tempest View from a GET route. The view function constructs the view with provided data.
```php
use Tempest\Router\Get;
use Tempest\View\View;
use function Tempest\View\view;
final readonly class AircraftController
{
#[Get(uri: '/aircraft/{aircraft}')]
public function show(Aircraft $aircraft, User $user): View
{
return view('./show.view.php',
aircraft: $aircraft,
user: $user,
);
}
}
```
--------------------------------
### Locating a Dependency Using `get()`
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/05-container.md
When constructor injection is not possible, use the `Tempest\Container\get()` function to resolve an object from the container. This should be used sparingly.
```php
use function Tempest\Container\get;
$config = get(AppConfig::class);
```
--------------------------------
### PHP Migration Class Example
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/packages/generation/tests/Php/__snapshots__/ClassGeneratorTest__creates_class_from_scratch__1.txt
This snippet demonstrates a PHP class implementing a migration interface. It defines an 'up' method to create a database table and a 'getName' method for the migration's identifier.
```php
primary()
->text('name');
}
public function getName(): string
{
return '0000-00-00_create_users_table';
}
}
```
--------------------------------
### Importing PHP Classes and Functions
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/4-internals/02-view-spec.md
Demonstrates how to import PHP namespaces and functions at the top of a view file for use within expressions.
```php
```
--------------------------------
### Combined Control Structures
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/4-internals/02-view-spec.md
Example of combining :foreach and :if expression attributes on a single element to conditionally render items within a loop.
```html
```
--------------------------------
### Create a Simple Console Command
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/packages/console/README.md
Define a basic console command class with a method annotated for console execution.
```php
final readonly class Hello
{
public function __construct(private Console $console) {}
#[ConsoleCommand]
public function world(): void
{
$this->console->writeln('Hello World!');
}
}
```
--------------------------------
### Get Specific Error Message for Field
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/2-features/03-validation.md
Specify a field name when calling `getErrorMessage()` to retrieve a localized message tailored for that specific field.
```php
$this->validator->getErrorMessage($failure, 'email');
// => 'Email must be a valid email address'
```
--------------------------------
### Flash Session Values
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/01-routing.md
Store a value in the session that lasts for the next request only using the flash() method. This example flashes a success message.
```php
public function store(Todo $todo): Redirect
{
$this->session->flash('message', value: 'Save was successful');
return new Redirect('/');
}
```
--------------------------------
### Initialize Tempest View Renderer with View Components
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/1-essentials/02-views.md
Configure the TempestViewRenderer with a ViewConfig object to enable view component support. Specify the paths to your component files.
```php
use Tempest\View\Renderers\TempestViewRenderer;
use Tempest\View\ViewConfig;
$config = new ViewConfig()->addViewComponents(
__DIR__ . '/components/x-base.view.php',
__DIR__ . '/components/x-footer.view.php',
__DIR__ . '/components/x-header.view.php',
);
$renderer = TempestViewRenderer::make($config);
```
--------------------------------
### Configure Responsive Images
Source: https://github.com/tempestphp/tempest-framework/blob/3.x/docs/3-packages/04-markdown.md
Set up the Markdown parser with a responsive image factory to generate srcset attributes for images.
```php
use Tempest\Markdown\Markdown;
use Tempest\ResponsiveImage\ResponsiveImageConfig;
use Tempest\ResponsiveImage\ResponsiveImageFactory;
$imageConfig = new ResponsiveImageConfig(
srcPath: __DIR__ . '/../resources/images',
publicPath: __DIR__ . '/../public',
);
$markdown = new Markdown(
imageFactory: new ResponsiveImageFactory($imageConfig),
);
```