### Create and Start Boson Application Source: https://github.com/boson-php/boson/blob/master/_autodocs/00-index.md Basic example of creating a Boson application, registering an event listener for application start, and starting the application. ```php on(ApplicationStarted::class, function() { echo "Application started!"; $app->window->title = "My Desktop App"; }); $app->start(); ``` -------------------------------- ### Register Event Listeners and Start Application Source: https://github.com/boson-php/boson/blob/master/_autodocs/00-index.md Example of registering listeners for application startup and shutdown events, followed by starting the application. ```php on(ApplicationStarting::class, function() { // Initialize }); $app->on(ApplicationStopping::class, function() { // Cleanup }); // Start with blocking call $app->start(); ``` -------------------------------- ### Complete Compilation Workflow Example Source: https://github.com/boson-php/boson/blob/master/_autodocs/07-compiler-and-tooling.md A comprehensive bash script demonstrating the full compilation workflow from project initialization to packaging for distribution. Includes configuration setup and platform-specific packaging commands. ```bash #!/bin/bash # 1. Initialize project php vendor/bin/boson init MyApp # 2. Configure boson.json cat > boson.json << 'EOF' { "application": { "name": "MyApp", "version": "1.0.0", "title": "My Desktop App" }, "includes": { "files": ["src/**/*.php"], "directories": ["resources/", "public/"] }, "targets": { "linux": {"architecture": "x86_64"}, "macos": {"architectures": ["x86_64", "arm64"]}, "windows": {"architecture": "x86_64"} } } EOF # 3. Compile for all platforms php vendor/bin/boson compile --config=boson.json # 4. Package for distribution php vendor/bin/boson pack --target=linux --format=tar.gz php vendor/bin/boson pack --target=macos --format=dmg php vendor/bin/boson pack --target=windows --format=exe # 5. Output in dist/ directory ls -la dist/ ``` -------------------------------- ### Boson Application Event Lifecycle Example Source: https://github.com/boson-php/boson/blob/master/_autodocs/06-event-listener-contracts.md A comprehensive example demonstrating the setup, runtime, and cleanup phases of an application using Boson's event listeners for ApplicationStarting, ApplicationStarted, and ApplicationStopping events. ```php on(ApplicationStarting::class, function(ApplicationStarting $event) { echo "Initializing...\n"; // Setup resources }); // Runtime phase - after start $app->on(ApplicationStarted::class, function(ApplicationStarted $event) { echo "Ready!\n"; // Start user-facing operations }); // Cleanup phase - before stop $app->on(ApplicationStopping::class, function(ApplicationStopping $event) { echo "Shutting down...\n"; // Clean resources }); // Start application and trigger events $app->start(); ``` -------------------------------- ### Install Boson Runtime Source: https://github.com/boson-php/boson/blob/master/_autodocs/00-index.md Install the core Boson runtime using Composer. ```bash composer require boson-php/runtime ``` -------------------------------- ### Install Boson Compiler Source: https://github.com/boson-php/boson/blob/master/_autodocs/00-index.md Install the Boson compiler for building and packaging applications using Composer. ```bash composer require boson-php/compiler ``` -------------------------------- ### Install Boson Symfony Bundle Source: https://github.com/boson-php/boson/blob/master/libs/bridge/symfony-bundle/README.md Install the Boson Symfony Bundle using Composer. ```bash composer require boson-php/symfony-bundle ``` -------------------------------- ### Start Boson Application in Laravel Route Source: https://github.com/boson-php/boson/blob/master/_autodocs/04-framework-bridges.md Initiate the Boson application within a Laravel route. This example shows how to retrieve the Boson application instance and start it. ```php // Create Boson application in routes Route::get('/app', function () { $boson = app(\Boson\Application::class); $boson->start(); }); ``` -------------------------------- ### Install Boson OS Info Package Source: https://github.com/boson-php/boson/blob/master/libs/component/os-info/README.md Install the Boson OS Info package using Composer. This command should be run in the root directory of your project. ```bash composer require boson-php/os-info ``` -------------------------------- ### Install Boson App Extension Alert Source: https://github.com/boson-php/boson/blob/master/libs/extension/app-ext-alert/README.md Install the Boson package using Composer. This command should be run in the root of your project. ```bash composer require boson-php/app-ext-alert ``` -------------------------------- ### Install Boson CPU Info Package Source: https://github.com/boson-php/boson/blob/master/libs/component/cpu-info/README.md Install the Boson CPU Info package using Composer. This command should be run in the root directory of your project. ```bash composer require boson-php/cpu-info ``` -------------------------------- ### Full Application Lifecycle and Usage Example Source: https://github.com/boson-php/boson/blob/master/_autodocs/05-core-application.md Demonstrates the complete application lifecycle from creation to shutdown, including event listener registration and basic UI manipulation. ```php on(ApplicationStarted::class, function() { echo "App started!\n"; // Access default window $window = $app->window; $window->title = 'Updated Title'; // Access webviews $webview = $app->webviews->primary; $webview->url = 'http://localhost:3000'; }); // Start the application (blocking) $app->start(); // Code here runs after application closes echo "Application closed\n"; ``` -------------------------------- ### Example Progress Step Source: https://github.com/boson-php/boson/blob/master/_autodocs/07-compiler-and-tooling.md Demonstrates creating and executing a progress step within a compilation workflow. Requires context for progress updates. ```php progress = 50; // 50% $step->execute($context); ``` -------------------------------- ### Install Boson Spiral Bridge Source: https://github.com/boson-php/boson/blob/master/libs/bridge/spiral-bridge/README.md Install the package using Composer. This command should be run in the root of your project. ```bash composer require boson-php/spiral-bridge ``` -------------------------------- ### Install Boson URI Package Source: https://github.com/boson-php/boson/blob/master/libs/component/uri/README.md Install the Boson URI package using Composer. This command should be run in the root of your project. ```bash composer require boson-php/uri ``` -------------------------------- ### Framework Integration Examples Source: https://github.com/boson-php/boson/blob/master/_autodocs/00-index.md Demonstrates how to use the Boson Application instance within controllers for Symfony and Laravel applications. ```php window; // Use Boson in controller } // Laravel Route::get('/app', function(Boson\Application $app) { $app->start(); }); ``` -------------------------------- ### Install Value Object Contracts Source: https://github.com/boson-php/boson/blob/master/libs/contracts/value-object-contracts/README.md Install the Boson PHP Value Object Contracts package using Composer. ```bash composer require boson-php/value-object-contracts ``` -------------------------------- ### Install Boson HTTP Bridge with Composer Source: https://github.com/boson-php/boson/blob/master/libs/bridge/http-bridge/README.md Use this command to install the Boson HTTP Bridge package in your project. ```bash composer require boson-php/http-bridge ``` -------------------------------- ### Install Boson HTTP Package Source: https://github.com/boson-php/boson/blob/master/libs/component/http/README.md Install the Boson HTTP package using Composer. This command should be run in the root of your project. ```bash composer require boson-php/http ``` -------------------------------- ### Registering Listener for ApplicationStarting Event Source: https://github.com/boson-php/boson/blob/master/_autodocs/06-event-listener-contracts.md Example of registering a listener for the ApplicationStarting event, which fires before the application begins its startup process. Useful for initialization tasks. ```php on(ApplicationStarting::class, function(ApplicationStarting $event) { // Perform startup initialization $config = loadConfig(); $database = connectDatabase($config); }); ``` -------------------------------- ### Identify Blocking Operations Source: https://github.com/boson-php/boson/blob/master/_autodocs/05-core-application.md Shows examples of operations that may block the event loop, such as starting the application or closing windows. ```php start(); // Blocking $window->close(); // May block ``` -------------------------------- ### Install Boson PHP Saucer Source: https://github.com/boson-php/boson/blob/master/libs/component/saucer/README.md Install the Boson package using Composer. This command should be run in the root directory of your project. ```bash composer require boson-php/saucer ``` -------------------------------- ### Install Boson URI Contracts via Composer Source: https://github.com/boson-php/boson/blob/master/libs/contracts/uri-contracts/README.md Use this command to install the Boson URI Contracts package in your project. ```bash composer require boson-php/uri-contracts ``` -------------------------------- ### Install Webview Extension Web Components Source: https://github.com/boson-php/boson/blob/master/libs/extension/webview-ext-web-components/README.md Install the Boson Webview Extension Web Components package using Composer. This command should be run in the root of your project. ```bash composer require boson-php/webview-ext-web-components ``` -------------------------------- ### Install Webview Extension Network Source: https://github.com/boson-php/boson/blob/master/libs/extension/webview-ext-network/README.md Install the Boson Webview Extension Network package using Composer. This command should be run in the root of your project. ```bash composer require boson-php/webview-ext-network ``` -------------------------------- ### Install Boson Event Listener Contracts Source: https://github.com/boson-php/boson/blob/master/libs/contracts/event-listener-contracts/README.md Install the Boson Event Listener Contracts package using Composer. This command should be run in the root of your project. ```bash composer require boson-php/event-listener-contracts ``` -------------------------------- ### Register and Trigger Application Events Source: https://github.com/boson-php/boson/blob/master/_autodocs/05-core-application.md Shows how to register an event listener for ApplicationStarted and start the application. ```php on(ApplicationStarted::class, function(ApplicationStarted $event) { echo "Application started!"; }); $app->start(); ``` -------------------------------- ### Install Boson HTTP Static Provider Source: https://github.com/boson-php/boson/blob/master/libs/component/http-static-provider/README.md Install the Boson HTTP Static Provider package using Composer. This command should be run in the root of your project. ```bash composer require boson-php/http-static-provider ``` -------------------------------- ### Install Webview Extension Battery Source: https://github.com/boson-php/boson/blob/master/libs/extension/webview-ext-battery/README.md Install the Boson Webview Extension Battery package using Composer. This command should be run in the root of your project. ```bash composer require boson-php/webview-ext-battery ``` -------------------------------- ### Install Boson Globals Provider Source: https://github.com/boson-php/boson/blob/master/libs/component/globals-provider/README.md Install the Boson Globals Provider package using Composer. This command should be run in the root of your project. ```bash composer require boson-php/globals-provider ``` -------------------------------- ### Install Boson URI Factory with Composer Source: https://github.com/boson-php/boson/blob/master/libs/component/uri-factory/README.md Install the Boson URI Factory package using Composer. This command should be run in the root of your project. ```bash composer require boson-php/uri-factory ``` -------------------------------- ### Compound Server Globals Provider Example Source: https://github.com/boson-php/boson/blob/master/_autodocs/08-supporting-components.md Demonstrates how to use CompoundServerGlobalsProvider to chain multiple server global providers. This is useful for combining static and default environment variables. ```php getServerGlobals($request); // Result: ['REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/api/users', ...] ``` -------------------------------- ### Registering Listener for ApplicationStarted Event Source: https://github.com/boson-php/boson/blob/master/_autodocs/06-event-listener-contracts.md Demonstrates registering a listener for the ApplicationStarted event, which fires after the application has successfully started and is ready for interaction. ```php on(ApplicationStarted::class, function(ApplicationStarted $event) { // Load UI resources $app->window->title = "Ready for Use"; }); ``` -------------------------------- ### Install Boson HTTP Contracts Source: https://github.com/boson-php/boson/blob/master/libs/contracts/http-contracts/README.md Install the Boson HTTP Contracts package using Composer. This command should be run in the root directory of your project. ```bash composer require boson-php/http-contracts ``` -------------------------------- ### PHP Configuration Object Example Source: https://github.com/boson-php/boson/blob/master/_autodocs/07-compiler-and-tooling.md Programmatically creates and configures a Boson application configuration object in PHP. Sets application metadata, include/exclude paths, and target platforms. ```php setApplicationName('MyApp'); $config->setApplicationVersion('1.0.0'); $config->setApplicationTitle('My Application'); // Add includes $config->addInclude(new FileIncludeConfiguration('src/index.php')); $config->addInclude(new DirectoryIncludeConfiguration('src/')); $config->addInclude(new DirectoryIncludeConfiguration('resources/')); // Add exclusions $config->addExclude('tests/**'); $config->addExclude('vendor/*/tests/'); // Add targets $factory = new BuiltinTargetFactory(); $config->addTarget($factory->createTarget('linux', 'x86_64')); $config->addTarget($factory->createTarget('macos', 'universal')); $config->addTarget($factory->createTarget('windows', 'x86_64')); return $config; ``` -------------------------------- ### Install Boson PHP PASM Package Source: https://github.com/boson-php/boson/blob/master/libs/component/pasm/README.md Install the Boson package using Composer. This command should be run in the root directory of your project. ```bash composer require boson-php/pasm ``` -------------------------------- ### Install Boson PHP ID Contracts Source: https://github.com/boson-php/boson/blob/master/libs/contracts/id-contracts/README.md Install the Boson ID Contracts package using Composer. This command should be run in the root of your project. ```bash composer require boson-php/id-contracts ``` -------------------------------- ### Install HTTP Body Decoder with Composer Source: https://github.com/boson-php/boson/blob/master/libs/component/http-body-decoder/README.md Install the Boson HTTP Body Decoder package using Composer. This command should be run in the root of your project. ```bash composer require boson-php/http-body-decoder ``` -------------------------------- ### Construct an HTTP Response Source: https://github.com/boson-php/boson/blob/master/_autodocs/03-http-components.md Shows how to build an HTTP response using Boson components. This example demonstrates creating a method, status code, and body, then assembling them into a `Response` object with specified headers. ```php 123])); // Build response components $response = new Response( statusCode: $status, headers: ['Content-Type' => 'application/json'], body: $body, ); ``` -------------------------------- ### Error Handling with Application and Window Exceptions Source: https://github.com/boson-php/boson/blob/master/_autodocs/05-core-application.md Illustrates robust error handling for common application issues, such as attempting to start without a default window or other application-level errors. ```php window)) { throw WindowDereferenceException::becauseNoDefaultWindow(); } $app->start(); } catch (WindowDereferenceException $e) { // Create new window $window = $app->windows->create(); $app->start(); } catch (ApplicationException $e) { error_log("Application error: " . $e->getMessage()); } ``` -------------------------------- ### Get Operating System Information Source: https://github.com/boson-php/boson/blob/master/_autodocs/08-supporting-components.md Retrieve details about the current operating system, such as its name, version, architecture, and platform, using the OperatingSystem::instance() method. ```php name(); // Linux echo "Version: " . $os->version(); // 5.10.0 echo "Arch: " . $os->architecture(); // x86_64 ``` -------------------------------- ### Firing Events Source: https://github.com/boson-php/boson/blob/master/_autodocs/06-event-listener-contracts.md Illustrates how events are fired, either by the framework itself (e.g., application start) or through explicit dispatching of custom events. ```php start(); // Custom events can be dispatched $dispatcher->dispatch(new MyCustomEvent()); ``` -------------------------------- ### Create HTTP Method Instance Source: https://github.com/boson-php/boson/blob/master/_autodocs/03-http-components.md Use the `create` method to instantiate HTTP methods. It handles both predefined constants like GET and POST, as well as custom method strings. ```php on(ApplicationStopped::class, function(ApplicationStopped $event) { // Perform final cleanup logApplicationShutdown(); }); ``` -------------------------------- ### URL Component Breakdown Example Source: https://github.com/boson-php/boson/blob/master/_autodocs/03-http-components.md Illustrates the structure of a request URL, breaking it down into its constituent components: scheme, user, password, host, port, path, query, and fragment. ```text https://user:pass@example.com:8080/api/users?id=123#section |______|____|____|___________|____|_________|_______|________| scheme user pass host port path query fragment ``` -------------------------------- ### Get CPU Information Source: https://github.com/boson-php/boson/blob/master/_autodocs/08-supporting-components.md Obtain information about the CPU, including the number of physical cores, logical processors, model name, and frequency, by instantiating CpuInfo. ```php coreCount(); // 8 echo "Threads: " . $cpu->logicalCount(); // 16 echo "Model: " . $cpu->model(); // Intel Core i7-9700K echo "Freq: " . $cpu->frequency() . " MHz"; // 3600 MHz ``` -------------------------------- ### Package Compiled Application Source: https://github.com/boson-php/boson/blob/master/_autodocs/07-compiler-and-tooling.md Create distributable application packages from compiled binaries. Supports various output formats like zip, tar.gz, dmg, and exe installers. ```bash php vendor/bin/boson pack --target=linux --format=zip ``` -------------------------------- ### Immutable HTTP Response Example Source: https://github.com/boson-php/boson/blob/master/_autodocs/09-boson-architecture.md Illustrates Boson's immutable-first design for HTTP objects, showing how methods like `withStatusCode` and `withHeader` return new instances instead of modifying the original. ```php // Evolving creates new instances $response1 = new Response(statusCode: 200); $response2 = $response1->withStatusCode(404); $response3 = $response2->withHeader('Content-Type', 'application/json'); // Original $response1 is unchanged ``` -------------------------------- ### Custom HttpAdapter Implementation Source: https://github.com/boson-php/boson/blob/master/_autodocs/02-http-bridge.md Extend the `HttpAdapter` abstract class to create a custom adapter for handling both request and response conversions. This example shows how to override methods like `getDecodedBody`, `getServerParameters`, and `getQueryParameters`. ```php getDecodedBody($request); $server = $this->getServerParameters($request); $query = $this->getQueryParameters($request); // Create custom request object return new CustomRequest($decoded, $server, $query); } public function createResponse(object $response): ResponseInterface { // Convert custom response to Boson response } } ``` -------------------------------- ### Boson Application Initialization Phase Source: https://github.com/boson-php/boson/blob/master/_autodocs/09-boson-architecture.md Details the steps during the application initialization phase, including constructor actions, event listener registration, and pre-start configuration. ```text 1. Application::__construct() ├─> Create ApplicationId ├─> Initialize WindowManager ├─> Initialize WebViewManager ├─> Initialize EventDispatcher └─> Load registered extensions 2. Register Event Listeners ├─> ApplicationStarting ├─> ApplicationStarted ├─> ApplicationStopping ├─> ApplicationStopped └─> Custom listeners 3. Pre-start Configuration ├─> Set window properties ├─> Load webviews URLs ├─> Configure dialogs └─> Setup event handlers ``` -------------------------------- ### Registering and Using a Custom Extension Source: https://github.com/boson-php/boson/blob/master/_autodocs/09-boson-architecture.md Demonstrates how to define a custom extension interface and implementation, register it with the application, and then retrieve and use it. ```php registerExtension(MyExtension::class); $extension = $app->extension(MyExtensionInterface::class); $extension->doSomething(); ``` -------------------------------- ### Instantiate Application and Access ID Source: https://github.com/boson-php/boson/blob/master/_autodocs/05-core-application.md Demonstrates how to create a new Application instance and retrieve its unique identifier. ```php id; // ApplicationId instance ``` -------------------------------- ### Manage Application Windows Source: https://github.com/boson-php/boson/blob/master/_autodocs/05-core-application.md Shows how to access the WindowManager and create new windows using the Application instance. ```php windows; $defaultWindow = $app->windows->default; // Create new window $newWindow = $app->windows->create(); ``` -------------------------------- ### Install Boson Laravel Provider Source: https://github.com/boson-php/boson/blob/master/libs/bridge/laravel-provider/README.md Install the Boson package using Composer in your Laravel project's root directory. ```bash composer require boson-php/laravel-provider ``` -------------------------------- ### Initialize New Boson Project Source: https://github.com/boson-php/boson/blob/master/_autodocs/07-compiler-and-tooling.md Create a new Boson project structure, including the boson.json configuration file, source directory, and .gitignore. This command sets up a basic project. ```bash php vendor/bin/boson init [project-name] ``` -------------------------------- ### Initialize and Compile Boson Application Source: https://github.com/boson-php/boson/blob/master/_autodocs/00-index.md Commands to initialize a Boson project configuration and compile it into an executable. ```bash # Create boson.json config php vendor/bin/boson init MyApp # Compile to executable php vendor/bin/boson compile ``` -------------------------------- ### Initialize Default Boson Configuration Source: https://github.com/boson-php/boson/blob/master/libs/bridge/symfony-bundle/README.md Dump the default Boson configuration to config/packages/boson.yaml. ```bash php ./bin/console config:dump-reference boson > config/packages/boson.yaml ``` -------------------------------- ### Boson Configuration File Source: https://github.com/boson-php/boson/blob/master/libs/bridge/spiral-bridge/README.md Create a 'boson.php' configuration file with the specified content. This file defines static file directories, the initial application URL, and application creation settings. ```php [ 'app/public', ], /** * The start application URL. */ 'init-url' => 'http://localhost/', /** * Application create configuration. */ 'application' => new \Boson\ApplicationCreateInfo( schemes: ['http'], debug: false, window: new \Boson\Window\WindowCreateInfo( title: 'My Application', resizable: true, webview: new \Boson\WebView\WebViewCreateInfo( contextMenu: true, ), ), ), ]; ``` -------------------------------- ### Registering and Dispatching ApplicationStarted Event Source: https://github.com/boson-php/boson/blob/master/_autodocs/06-event-listener-contracts.md Demonstrates how to register a listener for the ApplicationStarted event and how the application dispatches it. Assumes the application object implements EventListenerInterface. ```php on(ApplicationStarted::class, function(ApplicationStarted $event) { echo "Application has started!"; }); // Event is fired when application starts $app->start(); ``` -------------------------------- ### Install Laravel HTTP Bridge Source: https://github.com/boson-php/boson/blob/master/libs/bridge/laravel-http-bridge/README.md Install the Boson Laravel HTTP Bridge package using Composer. This command should be run in the root of your Laravel project. ```bash composer require boson-php/laravel-http-bridge ``` -------------------------------- ### Identifiable Interface and Implementation Example Source: https://github.com/boson-php/boson/blob/master/_autodocs/08-supporting-components.md Defines the IdentifiableInterface for objects that have a unique identifier and provides an example implementation 'MyService'. This contract is part of the value-object-contracts package. ```php id; } } ``` -------------------------------- ### Using Framework DI Container Source: https://github.com/boson-php/boson/blob/master/_autodocs/09-boson-architecture.md Demonstrates how to retrieve services from a PSR-11 compatible DI container within the Boson application. This is useful for accessing pre-configured services like databases. ```php // Framework DI containers can be used $database = $app->get('database-service'); // Custom services can be registered $app->set('my-service', function() { return new MyService(); }); ``` -------------------------------- ### Install Symfony HTTP Bridge Source: https://github.com/boson-php/boson/blob/master/libs/bridge/symfony-http-bridge/README.md Install the Boson PHP Symfony HTTP Bridge package using Composer. This command should be run in the root directory of your project. ```bash composer require boson-php/symfony-http-bridge ``` -------------------------------- ### Blocking Operations Source: https://github.com/boson-php/boson/blob/master/_autodocs/05-core-application.md Identifies operations that block the event loop, such as starting the application or waiting for windows to close. ```APIDOC ## Blocking Operations Boson uses the `BlockingOperation` marker trait to identify operations that block the event loop: **Namespace**: `Boson\Shared\Marker` **Operations**: - Starting the application - Waiting for windows to close - File dialogs - System dialogs ```php start(); // Blocking $window->close(); // May block ``` ``` -------------------------------- ### Install Boson Weak Types with Composer Source: https://github.com/boson-php/boson/blob/master/libs/component/weak-types/README.md Use this command to add the Boson Weak Types package to your project's dependencies. ```bash composer require boson-php/weak-types ``` -------------------------------- ### Configure Laravel Service Provider Source: https://github.com/boson-php/boson/blob/master/_autodocs/00-index.md Example of registering the Boson Laravel Service Provider in the Laravel application's config/app.php file. ```php [ \Boson\Bridge\Laravel\Provider\LaravelServiceProvider::class, ], ]; ``` -------------------------------- ### Handle HTTP Request and Response Source: https://github.com/boson-php/boson/blob/master/_autodocs/00-index.md Example of a PHP function that handles an incoming HTTP request, checks its method and URL, and returns a JSON response. ```php method->toString() === 'POST') { // Handle POST } // Access URL $path = $request->url->path; $query = $request->url->query; // Create response return (new Boson\Component\Http\Component\Response()) ->withStatusCode(200) ->withHeader('Content-Type', 'application/json') ->withBody(json_encode(['status' => 'ok'])); } ``` -------------------------------- ### Static File Provider Usage Source: https://github.com/boson-php/boson/blob/master/_autodocs/08-supporting-components.md Shows how to instantiate and use the StaticFileProvider to serve static files. It handles requests for files like CSS, JS, and images, returning a response if the file is found. ```php handle($request); if ($response !== null) { // Static file was served return $response; } // Not a static file, handle normally ``` -------------------------------- ### Attaching and Accessing Dynamic Properties Source: https://github.com/boson-php/boson/blob/master/_autodocs/05-core-application.md Demonstrates how to attach custom data and state to the application instance using dynamic properties, enabled by `#["AllowDynamicProperties"]`. ```php customData = ['key' => 'value']; $app->state = 'initialized'; // Access later echo $app->customData['key']; ``` -------------------------------- ### HttpAdapter Constructor Source: https://github.com/boson-php/boson/blob/master/_autodocs/02-http-bridge.md Initializes the HttpAdapter with optional server globals provider and body decoder. ```APIDOC ## HttpAdapter Constructor ### Description Initializes the HttpAdapter with optional server globals provider and body decoder. ### Method ```php public function __construct( ?ServerGlobalsProviderInterface $server = null, ?BodyDecoderInterface $body = null, ) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **$server** (ServerGlobalsProviderInterface|null) - Optional - Provider for PHP `$_SERVER` superglobal. If null, creates compound provider with static and default providers. - **$body** (BodyDecoderInterface|null) - Optional - Decoder for request body (`$_POST`). If null, creates factory with form-urlencoded and multipart decoders. ### Returns None ### Request Example ```php getDecodedBody($request); $server = $this->getServerParameters($request); $query = $this->getQueryParameters($request); // Create custom request object return new CustomRequest($decoded, $server, $query); } public function createResponse(object $response): ResponseInterface { // Convert custom response to Boson response } } // Example usage with default providers $adapter = new CustomAdapter(); // Example usage with custom providers $serverProvider = new CustomServerProvider(); $bodyDecoder = new CustomBodyDecoder(); $customAdapter = new CustomAdapter($serverProvider, $bodyDecoder); ``` ### Response #### Success Response None #### Response Example None ``` -------------------------------- ### Custom Framework HTTP Adapter Implementation Source: https://github.com/boson-php/boson/blob/master/_autodocs/02-http-bridge.md Extend the HttpAdapter base class to create a custom adapter for your framework. Implement createRequest to convert framework requests to Boson format and createResponse to convert Boson responses back to your framework's format. Ensure proper handling of request body and server parameters. ```php getDecodedBody($request), server: $this->getServerParameters($request), query: $this->getQueryParameters($request), ); } public function createResponse(object $response): ResponseInterface { if (!$response instanceof MyFrameworkResponse) { throw new \TypeError('Expected MyFrameworkResponse'); } // Convert to Boson ResponseInterface } } ``` -------------------------------- ### Resource Cleanup in Event Listeners Source: https://github.com/boson-php/boson/blob/master/_autodocs/06-event-listener-contracts.md Demonstrates how to perform resource cleanup using an event listener, specifically for the ApplicationStopping event, ensuring resources like database connections and caches are properly closed. ```php on(ApplicationStopping::class, function() { // Always clean up in stopping listener $database?->disconnect(); $cache?->flush(); removeTemporaryFiles(); }); ``` -------------------------------- ### Registering Listener for ApplicationStopping Event Source: https://github.com/boson-php/boson/blob/master/_autodocs/06-event-listener-contracts.md Shows how to register a listener for the ApplicationStopping event, which fires before the application shuts down. This is suitable for cleanup operations. ```php on(ApplicationStopping::class, function(ApplicationStopping $event) { // Save user data saveUserState(); closeDatabase(); }); ``` -------------------------------- ### Error Handling in Event Listeners Source: https://github.com/boson-php/boson/blob/master/_autodocs/06-event-listener-contracts.md Provides an example of implementing error handling within an event listener using a try-catch block to manage exceptions during resource initialization. ```php on(ApplicationStarted::class, function() { try { // Initialize resources initializeDatabase(); } catch (Exception $e) { error_log("Initialization failed: " . $e->getMessage()); // Consider if app should continue or fail } }); ``` -------------------------------- ### Registering Single and Multiple Event Listeners Source: https://github.com/boson-php/boson/blob/master/_autodocs/06-event-listener-contracts.md Demonstrates how to register a single listener for an event type and how to register multiple listeners for the same event. Listeners fire in the order they are registered. ```php on(ApplicationStarted::class, $listener); // Multiple listeners on same event $app->on(ApplicationStarted::class, $listener1); $app->on(ApplicationStarted::class, $listener2); // Listeners fire in registration order ``` -------------------------------- ### Cross-Platform Abstraction with Interfaces Source: https://github.com/boson-php/boson/blob/master/_autodocs/09-boson-architecture.md Shows how to define common interfaces for platform-agnostic functionality and obtain platform-specific implementations at runtime. This allows writing code that works across different operating systems. ```php extension(DialogExtension::class); $file = $dialog->openFile('Select image...'); ``` -------------------------------- ### Weak Reference Example for Event Dispatcher Source: https://github.com/boson-php/boson/blob/master/_autodocs/08-supporting-components.md Illustrates the use of WeakReference to manage listeners in an EventDispatcher. This prevents listeners from being garbage collected prematurely while still allowing them to be collected when no longer strongly referenced. ```php listeners[] = WeakReference::create($listener); } public function dispatch($event): void { foreach ($this->listeners as $ref) { if ($listener = $ref->get()) { $listener($event); } } } } ``` -------------------------------- ### Method Class Source: https://github.com/boson-php/boson/blob/master/_autodocs/03-http-components.md The Method class provides factory methods to create instances of HTTP methods. It supports predefined constants for standard methods (GET, POST, etc.) and allows for custom method creation. It also offers methods to retrieve methods by value or list all available cases. ```APIDOC ## Class: Method **Namespace**: `Boson\Component\Http\Component` **Implements**: `MethodInterface` ### Factory Method: create ```php public static function create(\Stringable|string $method): MethodInterface; ``` **Parameters**: - `$method` (`\Stringable`|`string`|`MethodInterface`) - HTTP method name or object **Returns**: `MethodInterface` — Predefined or custom method **Throws**: `InvalidMethodException` — If method string is empty **Description**: Creates an HTTP method instance. If the method matches a predefined constant (GET, POST, etc.), returns the corresponding constant. Otherwise, creates a custom method object. ### Factory Method: createMutable ```php public static function createMutable(\Stringable|string $method): MethodInterface; ``` **Description**: Same behavior as `create()`. Mutable HTTP methods are similar to immutable in Boson. ### Factory Method: tryFrom ```php public static function tryFrom(string $value): ?MethodInterface; ``` **Parameters**: - `$value` (`string`) - HTTP method name **Returns**: `MethodInterface|null` — Predefined method or null if not found **Description**: Attempts to find a predefined method matching the given value (case-insensitive). ### Factory Method: from ```php public static function from(string $value): MethodInterface; ``` **Parameters**: - `$value` (`string`) - HTTP method name **Returns**: `MethodInterface` — Predefined method **Throws**: `\ValueError` — If method not found ### Static Lookup: cases ```php public static function cases(): array; ``` **Returns**: `non-empty-list` — All predefined HTTP methods ### Predefined Methods All standard HTTP methods are available as class constants: GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, CONNECT. ```