### Starting the Resonance HTTP Server Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/getting-started/installation-and-requirements.md Run the `serve` command via the Resonance entry point script to start the built-in HTTP server, making the application accessible via HTTP. ```Shell php bin/resonance.php serve ``` -------------------------------- ### Starting Llama.cpp Server (Shell) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/tutorials/how-to-serve-llm-completions/index.md Example command to launch the llama.cpp server, specifying the model path, GPU layers, context size, parallel requests, continuous batching, memory locking, and port. Highlights the importance of `cont-batching` for parallel requests. ```shell ./server \ --model ~/llama-2-7b-chat/ggml-model-q4_0.gguf \ --n-gpu-layers 200000 \ --ctx-size 2048 \ --parallel 8 \ --cont-batching\ --mlock \ --port 8081 ``` -------------------------------- ### Installing Resonance Project via Composer Source: https://github.com/distantmagic/resonance/blob/master/README.md This command uses Composer's `create-project` functionality to set up a new project based on the `distantmagic/resonance-project` template. It's the recommended way to start a new Resonance application. ```Shell composer create-project distantmagic/resonance-project my-project ``` -------------------------------- ### Example SPF TXT DNS Record (Protonmail) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/tutorials/how-to-setup-postfix-for-outgoing-emails/index.md This is an example SPF record for a domain using Protonmail, indicating that emails are authorized if they originate from Protonmail's servers or the domain's MX records. It serves as a baseline before adding your server's IP. ```text Type: TXT Name: @ Value: v=spf1 include:_spf.protonmail.ch mx ~all ``` -------------------------------- ### Example CSS Entrypoint: app.css Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/asset-bundling-esbuild/accessing-entrypoints-in-php.md Provides an example of a CSS file used as an esbuild entrypoint, demonstrating font face definition and basic styling. ```css @font-face { font-family: "myfont"; src: url("../../resources/myfont.ttf") format("truetype"); } body { background-color: red; } ``` -------------------------------- ### Starting Resonance HTTP Server (Shell) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/tutorials/hello-world/index.md Command to start the built-in HTTP server provided by Resonance using the PHP executable. It runs the `resonance.php` script with the `serve` command. Expected output includes the server listening address and a "Hello, world!" message upon accessing the URL. ```shell $ php ./bin/resonance.php serve ``` -------------------------------- ### Example TypeScript Entrypoint: controller_homepage.ts Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/asset-bundling-esbuild/accessing-entrypoints-in-php.md Illustrates an example TypeScript file serving as an esbuild entrypoint, showing a simple import statement. ```typescript import common from "./common.ts"; // some application code // (...) ``` -------------------------------- ### Example TypeScript Entrypoint: controller_search.ts Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/asset-bundling-esbuild/accessing-entrypoints-in-php.md Shows another example TypeScript file acting as an esbuild entrypoint, similar to the homepage controller. ```typescript import common from "./common.ts"; // some application code // (...) ``` -------------------------------- ### Install Phinx with Composer Shell Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/database/migrations/index.md Demonstrates how to install the Phinx database migration tool using Composer. It suggests installing it in a separate directory (tools/phinx) to manage dependencies independently from the main application. ```shell $ composer require --working-dir=tools/phinx robmorgan/phinx ``` -------------------------------- ### Creating a New Resonance Project with Composer Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/getting-started/installation-and-requirements.md Use the Composer `create-project` command to initialize a new Resonance project directory with the recommended project structure and dependencies. ```Shell $ composer create-project distantmagic/resonance-project my-project ``` -------------------------------- ### Install Postfix on Debian-based Systems Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/tutorials/how-to-setup-postfix-for-outgoing-emails/index.md This command installs the Postfix mail transfer agent package on a Debian or Ubuntu Linux distribution using the apt package manager. It requires superuser privileges. ```shell $ sudo apt install Postfix ``` -------------------------------- ### Installing Standalone GraphQL Swoole Promise Adapter (Shell) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/graphql/standalone-promise-adapter.md This command installs the `distantmagic/graphql-swoole-promise-adapter` package using Composer. This is necessary if you want to use the Swoole Promise adapter for GraphQL independently without the full Resonance framework. ```shell $ composer require distantmagic/graphql-swoole-promise-adapter ``` -------------------------------- ### Example HTTP Controller with Route Parameter Binding (PHP) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/http/controllers.md Demonstrates a Resonance HTTP controller (`HttpController`) that handles a GET request for a blog post. It shows how to use the `#[RespondsToHttp]` attribute for routing and the `#[RouteParameter]` attribute within the `createResponse` method to automatically bind a route parameter (`blog_post_slug`) to a `BlogPost` entity, specifying the `CrudAction::Read` intent for authorization checks. ```php actor prompt<|im_end|> ``` -------------------------------- ### Testing Llama.cpp Completion via Resonance CLI (Shell) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/tutorials/how-to-serve-llm-completions/index.md Provides a shell command using the Resonance CLI (`resonance.php`) to send a prompt to the configured llama.cpp server and receive a completion response, verifying the setup. ```shell php ./bin/resonance.php llamacpp:completion "How to write a 'Hello, world' in PHP?" ``` -------------------------------- ### Example Translation File Content (INI) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/translations/index.md Provides an example `.ini` translation file (`app/lang/my.ini`) demonstrating simple key-value pairs and a section `[planet]`. Includes a string with a placeholder `:name`. ```ini hello = "world" greeting = "Hello, :name!" [planet] ours = "Earth" ``` -------------------------------- ### Defining a Simple HTTP Controller in PHP Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/index.md This PHP code snippet demonstrates how to define a basic HTTP controller function using attributes. It shows how to specify the HTTP method (GET) and URL pattern ('/') it responds to, and how it returns a Twig template. ```php #[RespondsToHttp( method: RequestMethod::GET, pattern: '/', )] function Homepage(ServerRequestInterface $request, ResponseInterface $response): TwigTemplate { return new TwigTemplate('website/homepage.twig'); } ``` -------------------------------- ### Install Swoole Futures with Composer (Shell) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/swoole-futures/standalone-usage.md Command to install the `distantmagic/swoole-futures` package using Composer when not using the full Resonance framework. ```shell $ composer require distantmagic/swoole-futures ``` -------------------------------- ### Generate and Install Self-Signed SSL Certificate and CA (Makefile) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/extras/ssl-certificate-for-local-development/index.md Provides a set of make targets to automate the process of generating a self-signed SSL certificate, a Certificate Authority (CA), and installing them into standard system directories. It utilizes openssl commands for key and certificate generation and the install command for file placement. Includes targets for cleaning generated files and updating system CA certificate stores. ```makefile PASS=yourcertificatemasterpassword SUBJ=/C=PL/ST=MyState/L=MyLocation/O=MyOrganization/OU=MyOrganisationUnit/CN=localhost/emailAddress=admin@localhost # Targets localhostCA.crt: localhostCA.pem openssl x509 \ -in localhostCA.pem \ -inform PEM \ -out localhostCA.crt localhostCA.key: openssl genrsa \ -des3 \ -out localhostCA.key \ -passout pass:$(PASS) \ 2048 localhostCA.pem: localhostCA.key openssl req \ -x509 \ -new \ -nodes \ -key localhostCA.key \ -sha256 \ -days 825 \ -out localhostCA.pem \ -passin pass:$(PASS) \ -subj "$(SUBJ)" localhost.key: openssl genrsa -out localhost.key 2048 localhost.csr: localhost.key openssl req \ -new \ -key localhost.key \ -out localhost.csr \ -subj "$(SUBJ)" localhost.crt localhostCA.srl: localhost.csr localhost.ext localhostCA.pem localhostCA.key openssl x509 \ -req \ -in localhost.csr \ -CA localhostCA.pem \ -CAkey localhostCA.key \ -CAcreateserial \ -out localhost.crt \ -days 825 \ -sha256 \ -passin pass:$(PASS) \ -extfile localhost.ext /etc/ssl/certs/localhost.crt: localhost.crt install localhost.crt /etc/ssl/certs/localhost.crt /etc/ssl/certs/localhostCA.crt: localhostCA.crt install localhostCA.crt /etc/ssl/certs/localhostCA.crt /etc/ssl/private/localhostCA.key: localhostCA.key install localhostCA.key /etc/ssl/private/localhostCA.key /etc/ssl/private/localhost.key: localhost.key install localhost.key /etc/ssl/private/localhost.key /etc/nginx/dhparam.pem: /etc/ssl/certs/localhost.crt /etc/ssl/private/localhost.key /etc/ssl/certs/localhostCA.crt /etc/ssl/private/localhostCA.key openssl dhparam -out /etc/nginx/dhparam.pem 4096 /usr/local/share/ca-certificates/localhostCA.crt: localhostCA.crt install localhostCA.crt /usr/local/share/ca-certificates/localhostCA.crt /usr/local/share/ca-certificates/localhost.crt: localhost.crt install localhost.crt /usr/local/share/ca-certificates/localhost.crt # PHONY targets .PHONY: clean clean: rm -f localhost.crt rm -f localhost.csr rm -f localhost.key rm -f localhostCA.crt rm -f localhostCA.key rm -f localhostCA.pem rm -f localhostCA.srl .PHONY: install install: /etc/ssl/certs/localhost.crt /etc/ssl/certs/localhostCA.crt /etc/ssl/private/localhost.key /etc/ssl/private/localhostCA.key .PHONY: uninstall uninstall: rm -f /etc/ssl/certs/localhost.crt rm -f /etc/ssl/certs/localhostCA.crt rm -f /etc/ssl/private/localhost.key rm -f /etc/ssl/private/localhostCA.key rm -f /usr/local/share/ca-certificates/localhost.crt rm -f /usr/local/share/ca-certificates/localhostCA.crt .PHONY: update-ca-certificates update-ca-certificates: /usr/local/share/ca-certificates/localhost.crt /usr/local/share/ca-certificates/localhostCA.crt /usr/sbin/update-ca-certificates ``` -------------------------------- ### Example Custom INI Configuration Section Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/configuration/index.md Shows the desired format for the custom '[manifest]' section in the config.ini file. ```ini ; ... [manifest] background_color = "#000000" theme_color = "#000000" ; ... ``` -------------------------------- ### Example Front Matter (YAML) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/generating-static-sites/page-structure.md An example of a YAML Front Matter block used at the top of a Markdown file to provide metadata for the page. It includes required fields like `layout`, `title`, and `description`. ```yaml --- layout: dm:document title: Example Document description: This document is about... --- ``` -------------------------------- ### Programmatic Llama.cpp Completion in Resonance (PHP) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/tutorials/how-to-serve-llm-completions/index.md Illustrates injecting the `LlamaCppClientInterface` into a PHP class, creating a `LlamaCppCompletionRequest`, and iterating over the streamed tokens returned by the `generateCompletion` method. Requires dependency injection setup. ```php llamaCppClient->generateCompletion($request); // each token is a chunk of text, usually few-several letters returned // from the model you are using foreach ($completion as $token) { swoole_error_log(SWOOLE_LOG_DEBUG, (string) $token); } } } ``` -------------------------------- ### Defining Homepage HTTP Responder (PHP) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/tutorials/hello-world/index.md Defines a simple HTTP Responder function `Homepage` in PHP using Resonance. It's annotated with `#[RespondsToHttp]` to map it to the root URL (`/`) for GET requests, associating it with the `HttpRouteSymbol::Homepage`. The function returns a `TwigTemplate` instance, indicating that the response will be rendered using the `homepage.twig` template. ```php sqlite = $builder->buildConnection(':memory:'); // This should select the currently installed SQLite-VSS version if // everything is installed correctly. $this->sqlite->query('SELECT vss_version()')->fetchArray(); } } ``` -------------------------------- ### Create DKIM TXT DNS Record Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/tutorials/how-to-setup-postfix-for-outgoing-emails/index.md This TXT record format is used to publish your domain's public key for DKIM email authentication. Replace placeholders with your specific selector and public key (without headers/footers). ```text Type: TXT Name: YOURDKIMSELECTOR._domainkey Value: v=DKIM1; k=rsa; p=YOURPUBLICKEY ``` -------------------------------- ### Run Doctrine Console Command (Shell) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/database/doctrine/console.md This shell command demonstrates how to execute the configured Doctrine console script (`bin/doctrine.php`). Running this command displays the Doctrine Command Line Interface help message, listing available commands and options, confirming that the setup is correct and the tool is ready for use. ```shell $ php ./bin/doctrine.php Doctrine Command Line Interface 2.16.2.0 Usage: command [options] [arguments] Options: -h, --help Display help for the given command. When no command is given display help for the list command -q, --quiet Do not output any message -V, --version Display this application version --ansi|--no-ansi Force (or disable --no-ansi) ANSI output -n, --no-interaction Do not ask any interactive question -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug Available commands: completion Dump the shell completion script help Display help for a command list List commands dbal dbal:reserved-words Checks if the current database contains identifiers that are reserved. dbal:run-sql Executes arbitrary SQL directly from the command line. (...) ``` -------------------------------- ### Linking Assets in PHP Template (Waterfall Example) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/asset-bundling-esbuild/preloading-assets.md This PHP template snippet shows a typical way to link CSS and JavaScript entry points using `$entryPoints->resolveEntryPointPath`. It illustrates the standard loading pattern that can lead to the waterfall effect where dependencies are discovered and loaded sequentially after the initial entry points. ```php-template
> ``` -------------------------------- ### Basic Standalone Swoole Future Usage (PHP) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/swoole-futures/standalone-usage.md Demonstrates how to create and resolve a `SwooleFuture` independently, showing how it works asynchronously within the Swoole event loop and how to access the result. Requires `Swoole\Coroutine\run` to start the loop. ```php resolve(2)->result + 3); }); ``` -------------------------------- ### Sending Email via Resonance CLI Shell Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/tutorials/how-to-setup-postfix-for-outgoing-emails/index.md Demonstrates sending an email using the Resonance command-line tool. Specifies the sender, recipient, subject, transport (Postfix), and body of the email as command-line arguments. Requires the Resonance application to be set up and the `mail:send` command available. ```shell $ php bin/resonance.php mail:send \ --from "me@YOURDOMAIN" \ --to "you@YOURDOMAIN" \ --subject "Hello!" \ --transport "postfix" \ "How is it going?" ``` -------------------------------- ### Defining Services with Dependency Injection in PHP Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/index.md This PHP code shows how to define a service (Logger) using the #[Singleton] attribute in Resonance. The 'provides' argument specifies the interface implemented, allowing the framework to automatically manage dependencies without manual configuration. ```php #[Singleton(provides: LoggerInterface::class)] readonly class Logger implements LoggerInterface { public function log($level, string|Stringable $message, array $context = []): void { // ... } } ``` -------------------------------- ### Configure Doctrine Console with Resonance (PHP) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/database/doctrine/console.md This PHP script serves as the entry point for running Doctrine console commands within the Resonance framework. It requires the autoloader and invokes the `DoctrineConsoleRunner::run()` method to initialize Doctrine with Resonance's specific configuration, enabling access to Doctrine commands tailored for the application's setup. ```php mailer->get('postfix')->enqueue($email); ``` -------------------------------- ### Implementing GraphQL Authorization Gate (PHP) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/graphql/developing-schema.md This PHP class implements a `SiteActionGate` for the `SiteAction::UseGraphQL` in the Resonance framework. Annotated with `#[DecidesSiteAction]` and `#[Singleton]`, it provides the `can` method to define authorization rules. The example shows a simple implementation that always returns `true`, but this is where custom authorization logic would be added. ```php new StringConstraint(),\n 'port' => new IntegerConstraint(),\n ],\n);\n\n$constraint->validate([\n 'host' => 'http://example.com',\n 'port' => 3306,\n]); ``` -------------------------------- ### Creating the Configuration Provider in PHP Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/configuration/index.md Implements a ConfigurationProvider to read, validate, and instantiate the ManifestConfiguration from the 'manifest' section of the INI file using constraints. ```php */ #[Singleton(provides: ManifestConfiguration::class)] final readonly class ManifestConfigurationProvider extends ConfigurationProvider { public function getConstraint(): Constraint { return new ObjectConstraint( properties: [ 'background_color' => new StringConstraint(), 'theme_color' => new StringConstraint(), ], ); } protected function getConfigurationKey(): string { return 'manifest'; } protected function provideConfiguration($validatedData): ManifestConfiguration { return new ManifestConfiguration( backgroundColor: $validatedData['background_color'], themeColor: $validatedData['theme_color'], ); } } ``` -------------------------------- ### Example GraphQL Response Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/graphql/developing-schema.md This JSON snippet shows the expected response structure when executing the example GraphQL query. It contains the 'data' field with the result of the 'ping' query, including the 'message' field with the value 'pong'. ```json { "data": { "ping": { "message": "pong" } } } ``` -------------------------------- ### Running esbuild with Metafile Output (Shell) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/asset-bundling-esbuild/index.md This shell command demonstrates how to run esbuild to bundle a JavaScript file (`app.js`), output the bundled result to `out.js`, and generate a `meta.json` file containing build metadata. The metafile is crucial for Resonance's integration features. ```shell $ esbuild app.js --bundle --metafile=meta.json --outfile=out.js ``` -------------------------------- ### Using Resonance SessionManager (PHP) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/http/sessions.md Demonstrates the typical 'start -> modify -> persist' pattern for using the Resonance SessionManager. It shows how to start a session, add data using the `put` method, and explicitly persist the session data to storage (Redis). Note that persistence is automatic in Responders/Controllers. ```php start()` also sets the session cookie in the response. * * @var Resonance\Session $session * @var Psr\Http\Message\ServerRequestInterface $request * @var Swoole\Http\Response $response */ $session = $sessionManager->start($request); /** * Anything that is serializable by igbinary can be used as a value. */ $session->data->put('my-data-key', 'my-value'); /** * Only now the session data is persisted and stored in the Redis database. * Just setting the data in `$session->data` does not persist that data. */ $sessionManager->persistSession($request); ``` -------------------------------- ### Programmatically Generating Static Sites with Resonance PHP Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/generating-static-sites/index.md Demonstrates how to programmatically use the StaticPageProcessor class to build static sites. This script sets up the Dependency Injection Container, registers singletons, and runs the static page processing within a Swoole coroutine. Requires the project's autoloader and the DM_ROOT constant to be defined. ```php phpProjectFiles->indexDirectory(DM_RESONANCE_ROOT); $container->phpProjectFiles->indexDirectory(DM_APP_ROOT); $container->registerSingletons(); $staticPageProcessor = $container->make(StaticPageProcessor::class); /** * @var bool */ $coroutineResult = run(static function () use ($staticPageProcessor) { $staticPageProcessor->process(); }); exit((int) !$coroutineResult); ``` -------------------------------- ### Initializing Task Conversation Controller (PHP) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/tutorials/semi-scripted-conversational-applications/index.md Sets up the `TaskConversationController` class, injecting dependencies and defining the initial dialogue node (`rootNode`). It configures potential responses, including a catch-all and specific responses triggered by LlamaCpp analysis for creating or listing tasks. ```php #[Singleton] readonly class TaskConversationController extends DialogueController { private DialogueNodeInterface $rootNode; public function __construct( private DoctrineEntityManagerRepository $doctrineEntityManagerRepository, private HelpfulAssistant $helpfulAssistantPersona, private LlamaCppClientInterface $llamaCppClient, LlamaCppExtractWhenInterface $llamaCppExtractWhen, private LlamaCppExtractSubject $llamaCppExtractSubject, ) { $this->rootNode = DialogueNode::withMessage('Hello! How can I help you with your tasks?'); $this->rootNode->addPotentialResponse(new CatchAllResponse( followUp: $this->welcomeNode, )); $this->welcomeNode->addPotentialResponse(new LlamaCppExtractWhenResponse( llamaCppExtractWhen: $llamaCppExtractWhen, condition: 'User wants to create a new task', persona: $helpfulAssistantPersona, whenProvided: $this->whenUserWantsToCreateTask(...) )); $this->welcomeNode->addPotentialResponse(new LlamaCppExtractWhenResponse( llamaCppExtractWhen: $llamaCppExtractWhen, condition: 'User wants to list all their tasks', persona: $helpfulAssistantPersona, whenProvided: $this->whenUserWantsToListAllTasks(...) )); } public function getRootDialogueNode(): DialogueNodeInterface { return $this->rootNode; } // (...) ``` -------------------------------- ### Configuring Resonance for Llama.cpp (INI) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/tutorials/how-to-serve-llm-completions/index.md Shows the INI configuration required in Resonance to specify the host and port where the llama.cpp server is running, allowing Resonance to connect to it. ```ini [llamacpp] host = 127.0.0.1 port = 8081 ``` -------------------------------- ### Configure Phinx Connection with DI PHP Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/database/migrations/index.md Provides a configuration file (phinx.php) for Phinx that uses Resonance's Dependency Injection Container to fetch database connection details. It boots the container, retrieves the DatabaseConfiguration, and populates the Phinx environment settings with details from the 'default' connection pool. ```php connectionPoolConfiguration ->get('default') ; return [ 'paths' => [ 'migrations' => '%%PHINX_CONFIG_DIR%%/migrations', 'seeds' => '%%PHINX_CONFIG_DIR%%/seeds', ], 'environments' => [ 'default_migration_table' => 'phinxlog', 'default_environment' => 'mysql', 'mysql' => [ 'adapter' => $connectionPoolConfiguration->driver->value, 'host' => $connectionPoolConfiguration->host, 'name' => $connectionPoolConfiguration->database, 'user' => $connectionPoolConfiguration->username, 'pass' => $connectionPoolConfiguration->password, 'port' => $connectionPoolConfiguration->port, 'charset' => 'utf8', ], ], 'version_order' => 'creation', ]; }); ``` -------------------------------- ### Forwarding HTTP Requests with Redirect Responder (PHP) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/http/responders.md HTTP Responders can forward requests to other responders by returning another responder from the `respond` method. For example: ```PHP build(__DIR__.'/esbuild-meta.json'); $entryPoints = new EsbuildMetaEntryPoints($esbuildMeta); $entryPointPath = $entryPoints->resolveEntryPointPath('controller_homepage.ts'); ``` -------------------------------- ### Logger Collection Dependency Graph (Graphviz DOT) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/dependency-injection/index.md Illustrates the dependency flow for the logger collection example, showing how individual loggers are aggregated by the provider. ```Graphviz DOT digraph { ConsoleLogger -> LoggerAggregateProvider; RemoteLogger -> LoggerAggregateProvider; LoggerAggregateProvider -> LoggerAggregate; } ``` -------------------------------- ### Example YAML Frontmatter for a Page Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/generating-static-sites/markdown-extensions.md Illustrates the standard YAML frontmatter used in Resonance Markdown files to define page metadata like title, description, and layout. ```yaml --- title: My Page description: My Description layout: dm:document --- Hello! ``` -------------------------------- ### Adding CSRF Token to HTML Meta Tag (Twig) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/websockets/protocols.md Example Twig template code showing how to render a CSRF token into an HTML meta tag, making it accessible to client-side JavaScript. ```twig ``` -------------------------------- ### Example GraphQL Query Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/graphql/developing-schema.md This GraphQL query demonstrates how to fetch the 'message' field from the 'ping' root query field defined in the PHP code. It shows the basic structure for querying a field that returns an ObjectType. ```graphql query Ping() { ping { message } } ``` -------------------------------- ### Building DI Container with Resonance PHP Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/dependency-injection/index.md Shows the default `bin/resonance.php` file used to initialize the Dependency Injection container in Resonance. It demonstrates enabling Swoole coroutines, creating the container, indexing application and framework files, registering singletons, and running the console application. ```php phpProjectFiles->indexDirectory(DM_RESONANCE_ROOT); $container->phpProjectFiles->indexDirectory(DM_APP_ROOT); $container->registerSingletons(); exit($container->make(ConsoleApplication::class)->run()); ``` -------------------------------- ### WebSocket Connection Flow Diagram (Graphviz) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/websockets/server.md This Graphviz snippet defines a diagram illustrating the sequence of events when establishing a WebSocket connection, starting from an HTTP request, through the handshake and upgrade, to the open connection and protocol-based message processing. ```graphviz digraph { Handshake [label="Handshake"]; HTTPRequest [label="HTTP Request"]; Open [label="WebSocket Connection Opened"]; Protocol [label="Process Incoming Messages According to the Selected Protocol" shape="rectangle"]; Upgrade [label="Upgrade Connection to WebSocket"]; WebSocketServerController [label="WebSocketServerController"]; HTTPRequest -> WebSocketServerController -> Handshake -> Upgrade -> Open -> Protocol ; } ``` -------------------------------- ### Querying Multiple Blog Posts (GraphQL) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/tutorials/basic-graphql-schema/index.md Demonstrates how to query multiple instances of the same type ('blogPost') with different arguments ('slug') in a single GraphQL query, aliasing the results ('post1', 'post2'). ```graphql query BlogPosts() { post1: blogPost(slug: "foo") { content } post2: blogPost(slug: "bar") { content } } ``` -------------------------------- ### Returning Twig Template from PHP Responder Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/docs/features/templating/twig/rendering-templates.md Demonstrates how to create an HTTP responder in PHP that returns a TwigTemplate instance, specifying the template file name. This responder is configured to handle GET requests to the '/twig' path. ```php addPotentialResponse(new LlamaCppExtractWhenResponse( llamaCppExtractWhen: $llamaCppExtractWhen, condition: 'User says they want to play a board game', followUp: function (LlamaCppExtractWhenResult $result) { return new DialogueResponseResolution( followUp: DialogueNode::withMessage("Great! Let's play board games."), status: DialogueResponseResolutionStatus::CanRespond, ); }, )); $initialNode->addPotentialResponse(new LlamaCppExtractWhenResponse( llamaCppExtractWhen: $llamaCppExtractWhen, condition: 'User says they want to play sports', followUp: function (LlamaCppExtractWhenResult $result) { return new DialogueResponseResolution( followUp: DialogueNode::withMessage("Great! Let's play sports."), status: DialogueResponseResolutionStatus::CanRespond, ); }, )); $initialNode->addPotentialResponse(new CatchAllResponse( followUp: DialogueNode::withMessage("Sorry, I can't play that."), )); $initialNode->respondTo(new UserInput('I want to play basketball.')); ``` -------------------------------- ### Creating GraphQL HTTP Responder (PHP) Source: https://github.com/distantmagic/resonance/blob/master/docs/pages/tutorials/basic-graphql-schema/index.md Defines a PHP class 'GraphQL' that acts as an HTTP responder for POST requests to '/graphql'. It uses Resonance attributes ('#[RespondsToHttp]', '#[Singleton]') to configure routing and dependency injection, delegating the actual GraphQL response handling to a injected 'ResonanceGraphQL' service. ```php graphql; } } ```