### CLI Module Example Usage Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/ContextModules.md Shows the command-line format for interacting with the application using the CliModule, including examples for GET and POST requests. ```bash php index.php get /users php index.php post /users name=John ``` -------------------------------- ### Initialize Application Instance Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/README.md Provides a PHP code example for initializing a BEAR.Package application using the Injector. It demonstrates how to get an instance of the application and run a request. ```php use BEAR\Package\Injector; $injector = Injector::getInstance( 'MyVendor\MyApp', // app name 'prod-api-app', // context '/path/to/app', // app directory $cache // optional PSR-6 cache ); $app = $injector->getInstance(AppInterface::class); $response = $app->run('get', '/users/1'); ``` -------------------------------- ### Context-Based Configuration Examples Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/README.md Demonstrates how context strings are used to configure applications by mapping segments to modules that override bindings. Shows examples of context segments and their loading order. ```php // Context segments (right-to-left loading order): 'prod-api-app' // app → api → prod 'dev-cli-app' // app → cli → dev 'prod-hal-app' // app → hal → prod 'prod-cache-auth' // app → auth → cache → prod (custom) ``` -------------------------------- ### Example CLI Output with Data Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/CliResponder.md A concrete example of the CLI output, showing a 200 OK status, Content-Type header, and a JSON body. ```text 200 OK Content-Type: application/json X-Custom-Header: value {"id": 1, "name": "John"} ``` -------------------------------- ### Install Dependencies Source: https://github.com/bearsunday/bear.package/blob/1.x/demo/README.md Use this command to install project dependencies via Composer. ```bash composer install ``` -------------------------------- ### Custom WebRouter Binding Example Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/configuration.md Example of how to bind a custom host for the WebRouter in a production module. ```php class ProdModule extends AbstractAppModule { protected function configure(): void { $this->bind() ->annotatedWith(DefaultSchemeHost::class) ->toInstance('https://api.example.com'); } } ``` -------------------------------- ### Run Web Server Source: https://github.com/bearsunday/bear.package/blob/1.x/demo/README.md Start a local web server using Composer for development. Access the application via the provided URL. ```bash composer serve # http://127.0.0.1:8080/ ``` -------------------------------- ### Optional .compile.php File Example Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/configuration.md An optional .compile.php file can be placed in the application's root directory for pre-compilation setup, such as defining null object classes. ```php // {appDir}/.compile.php class NullUser extends User { // Null object pattern } ``` -------------------------------- ### Custom Logger Setup with StreamHandler Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/LoggingAndCompilation.md Provides an example of setting up a custom logger that writes to standard error using Monolog's StreamHandler. This is useful for redirecting logs in specific environments. ```php use Psr\Log\LoggerInterface; use Monolog\Logger; use Monolog\Handler\StreamHandler; class CustomLoggerProvider implements ProviderInterface { public function get(): LoggerInterface { $logger = new Logger('app'); $logger->pushHandler(new StreamHandler('php://stderr')); return $logger; } } // In ProdModule class ProdModule extends AbstractAppModule { protected function configure(): void { $this->bind(LoggerInterface::class) ->toProvider(CustomLoggerProvider::class) ->in(Scope::SINGLETON); } } ``` -------------------------------- ### CompileReport Example Usage Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/types.md Provides an example of a CompileReport array, illustrating the expected format and data types for each key. ```php [ 'time' => '2.45', 'memory' => '128.500', 'compiled' => 15, 'preload' => '/app/preload.php (overwritten)', 'dot' => '/app/var/di/prod-app/Graph.dot' ] ``` -------------------------------- ### CLI Usage Examples Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/README.md Execute API requests via the command line using various HTTP methods and parameters. ```bash # Get request php index.php get /users ``` ```bash # Post request with parameters php index.php post /users name=John age=30 ``` ```bash # Method override php index.php put /users/1 name=Jane ``` ```bash # Delete request php index.php delete /users/1 ``` -------------------------------- ### Extract GET Request Details Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/HttpMethodParams.md Use the get method to extract the HTTP method and parameters for a GET request. This example shows how to process $_SERVER and $_GET superglobals. ```php // GET request [$method, $params] = $params->get( ['REQUEST_METHOD' => 'GET'], ['id' => '1', 'name' => 'John'], [] ); // Result: ['get', ['id' => '1', 'name' => 'John']] ``` -------------------------------- ### Module Loading Order Example Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/ContextModules.md Illustrates the loading order of context modules based on a reversed split of the context string, showing how later modules override earlier ones. ```text Context: "prod-api-app" Split: ["prod", "api", "app"] Reversed: ["app", "api", "prod"] Load Order: 1. AppModule (or PackageModule base) 2. ApiModule (overrides default scheme) 3. ProdModule (overrides error pages, enables caching) ``` -------------------------------- ### Typical Usage Flow: CLI Usage Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/00-Overview.md Provides examples of how to interact with a BEAR.Package application using the command-line interface. ```APIDOC ## Typical Usage Flow: CLI Usage ### CLI Usage ```bash # Requires 'cli' context php public/index.php get /users php public/index.php post /users name=John php public/index.php put /users/1 name=Jane php public/index.php delete /users/1 ``` ``` -------------------------------- ### Application Metadata Example Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/configuration.md Instantiate the Meta class with application namespace, context, and root directory. The derived directory paths are then accessible as public properties. ```php $meta = new Meta('MyVendor\MyApp', 'prod-api-app', '/var/www/myapp'); // meta->varDir = '/var/www/myapp/var' // meta->logDir = '/var/www/myapp/var/log' // meta->tmpDir = '/var/www/myapp/var/tmp' // meta->cacheDir = '/var/www/myapp/var/tmp/cache' ``` -------------------------------- ### Compilation CLI Usage Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/LoggingAndCompilation.md Example of using the framework-provided bin/bear.compile script to compile application modules for production. Shows the command and expected output. ```bash # Via framework-provided bin/bear.compile script ./bin/bear.compile 'MyVendor\MyApp' prod-app /path/to/app # Output: # Compilation (1/2): FakeRun took 0.45 seconds and used 64.123MB of memory # preload.php: /app/preload.php # Compilation (2/2): DumpAutoload took 1.25 seconds and used 128.500MB of memory # autoload.php: /app/var/autoload.php ``` -------------------------------- ### Custom Logger Binding Example Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/configuration.md Example of binding a custom logger provider in a production module, ensuring singleton scope. ```php class ProdModule extends AbstractAppModule { protected function configure(): void { $this->bind(LoggerInterface::class) ->toProvider(CustomLoggerProvider::class) ->in(Scope::SINGLETON); } } ``` -------------------------------- ### Application Configuration Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/00-Overview.md Covers classes for configuring application imports and multi-app setups. ```APIDOC ## Application Configuration This section describes how to configure application imports and multi-app setups. ### ImportApp **Purpose**: Configure app import/multi-app setup. **Usage**: `new ImportApp('host', 'Vendor\App', 'context')` ### ImportAppModule **Purpose**: Enable resource imports from other apps. **Usage**: `new ImportAppModule([...])` ``` -------------------------------- ### Example CLI Output Format Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/CliResponder.md Illustrates the expected text format for CLI output, including status code, text, headers, and the resource body. ```text {code} {status_text} {header1}: {value1} {header2}: {value2} {body} ``` -------------------------------- ### HAL Module Example Response Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/ContextModules.md Presents an example of a HAL+JSON response structure, including hypermedia links and embedded resources, as configured by the HalModule. ```json { "name": "John", "age": 30, "_links": { "self": { "href": "/users/1" }, "profile": { "href": "/users/1/profile" } }, "_embedded": { "friends": [...] } } ``` -------------------------------- ### Preload File Example Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/LoggingAndCompilation.md Shows the structure of a generated preload.php file, which includes all loaded classes for opcache preloading. This file is crucial for optimizing application startup time. ```php bind('app-name') ->toInstance($this->appMeta->name); $this->bind('log-dir') ->toInstance($this->appMeta->logDir); // Bind custom services $this->bind(LoggerInterface::class) ->to(CustomLogger::class) ->in(Scope::SINGLETON); } } ``` -------------------------------- ### Dependency Injection Example for CliResponder Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/CliResponder.md Shows how to obtain an instance of CliResponder via a DI container in a CLI context. This responder implements the TransferInterface. ```php use BEAR\Package\Provide\Transfer\CliResponder; // Injected via DI container in CLI context $responder = $injector->getInstance(TransferInterface::class); ``` -------------------------------- ### Log Format Example Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/LoggingAndCompilation.md Illustrates the standard format for log entries, including datetime, level, message, and context. Useful for parsing and understanding log data. ```text [2024-01-15 10:30:45] ERROR: User not found for ID:1 {"exception":"UserNotFoundException"} [2024-01-15 10:30:46] DEBUG: Cache hit for key:user_1 {} ``` -------------------------------- ### API Context Module Example Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/ContextModules.md Illustrates the effect of the ApiModule on resource URIs, changing them from http://host to app://self for inter-service communication. ```php // Without api context $router->match(...); // Result: "http://localhost/users/1" // With api context (prod-api-app) // Result: "app://self/users/1" ``` -------------------------------- ### Opcache Preload Configuration Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/LoggingAndCompilation.md Example php.ini configuration to enable opcache preloading using the generated preload.php file. Ensure opcache.preload and opcache.preload_user are correctly set. ```ini [opcache] opcache.preload=/app/preload.php opcache.preload_user=www-data ``` -------------------------------- ### Query Parameter Normalization Example Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/configuration.md Demonstrates how parse_str() can create numeric keys, which are then filtered out by QueryParamNormalizer as they are invalid in HTTP parameters. ```php parse_str('0=foo&name=bar', $result); // $result = [0 => 'foo', 'name' => 'bar'] // After normalization: ['name' => 'bar'] (numeric key filtered) ``` -------------------------------- ### CliResponder Usage Example Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/CliResponder.md Demonstrates how to use CliResponder in a CLI context after obtaining a resource. It calls the responder with the resource object and $_SERVER array. ```php // In CLI context $resource = $resource->uri('page://self/users/1')(); $responder = $injector->getInstance(TransferInterface::class); $responder($resource, $_SERVER); // Output: // 200 OK // Content-Type: application/hal+json // // {"name": "John", "_links": {...}} ``` -------------------------------- ### Context-Based Module Override Example Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/configuration.md Shows how an application-specific module can override a framework binding. This example overrides the ErrorPageFactoryInterface binding in the ProdModule. ```php // {AppName}\Module\ProdModule overrides framework ProdModule class ProdModule extends AbstractAppModule { protected function configure(): void { // This overrides framework binding $this->bind(ErrorPageFactoryInterface::class) ->to(CustomErrorPageFactory::class); } } ``` -------------------------------- ### ContextScheme Annotation Usage Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Annotations.md Example of using the #[ContextScheme] annotation to define a context-aware scheme binding. ```php use BEAR\Resource\Annotation\ContextScheme; #[ContextScheme] string $scheme = 'app://self'; ``` -------------------------------- ### AppName Annotation Usage Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Annotations.md Example of using the #[AppName] annotation to specify the application namespace. ```php use BEAR\Resource\Annotation\AppName; #[AppName] string $appName = 'MyVendor\MyApp'; ``` -------------------------------- ### Configure DI Module with Context Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Module.md Instantiate the Module and use its `__invoke` method to get a configured DI module. Provide application metadata and a hyphenated context string. The context string determines which modules are loaded and in what order, with later modules overriding earlier ones. ```php use BEAR\ ``` -------------------------------- ### Create CreatedResourceInterceptor Instance Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/CreatedResourceInterceptor.md Instantiates the CreatedResourceInterceptor. Requires a CreatedResourceRenderer instance for its operation. This is typically done during module installation. ```php use BEAR\Package\Provide\Representation\CreatedResourceInterceptor; use BEAR\Package\Provide\Representation\CreatedResourceRenderer; $interceptor = new CreatedResourceInterceptor( new CreatedResourceRenderer($router, $resource) ); ``` -------------------------------- ### Instantiate Compiler Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Compiler.md Creates a new Compiler instance. It requires the application's namespace, context, and root directory. The 'prepend' option controls whether the autoloader is registered at the start of the SPL stack. ```php use BEAR\Package\Compiler; $compiler = new Compiler( 'MyVendor\MyApp', 'prod-app', '/path/to/app' ); ``` -------------------------------- ### Resource URI Format Examples Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/README.md Illustrates the different formats for resource URIs used within BEAR.Package, including web pages, API resources, imported app resources, and external APIs. ```php // Resource URI format page://self/users // Web page app://self/api/users // API resource app://user-app/api/users // Imported app resource http://api.example.com/ // External API ``` -------------------------------- ### DefaultSchemeHost Annotation Usage Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Annotations.md Example of using the #[DefaultSchemeHost] annotation to specify the default scheme and host for routing. ```php use BEAR\Sunday\Annotation\DefaultSchemeHost; #[DefaultSchemeHost] string $schemeHost = 'http://localhost'; ``` -------------------------------- ### Override Options Method in ProdModule Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/ContextModules.md Demonstrates how to override the default behavior of disabling the OPTIONS method in ProdModule by installing OptionsMethodModule. ```php class ProdModule extends AbstractAppModule { protected function configure(): void { parent::configure(); $this->install(new OptionsMethodModule()); } } ``` -------------------------------- ### StdIn Annotation Binding Example Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Annotations.md Illustrates how the #[StdIn] annotation is bound to a temporary file path during CliModule configuration for CLI input, and how it's used to write parameters. ```php // CliModule binding $stdIn = tempnam(sys_get_temp_dir(), 'stdin-' . crc32(__FILE__)); $this->bind()->annotatedWith(StdIn::class)->toInstance($stdIn); // CliRouter usage public function __construct( #[StdIn] private string $stdIn = '' ) {} // Write CLI params to stdin for PUT/PATCH/DELETE file_put_contents($this->stdIn, http_build_query($query)); ``` -------------------------------- ### Compiled DI Configuration Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/LoggingAndCompilation.md Example of configuring the Injector to use the production context for compiled Dependency Injection. This leads to faster instantiation by avoiding reflection and file scanning at runtime. ```php // Use prod context Injector::getInstance('App', 'prod-app', '/app'); ``` -------------------------------- ### JSON Request Body Example Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/00-Overview.md Illustrates sending data in a JSON format within the request body. Ensure the `Content-Type` header is set to `application/json`. ```php POST /users Content-Type: application/json {"name": "John", "age": 30} ``` -------------------------------- ### StdIn Annotation Usage in Constructor Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Annotations.md Example of injecting the stdin stream path using the #[StdIn] annotation in a class constructor, typically for CLI applications. ```php use BEAR\Package\Annotation\StdIn; class CliRouter { public function __construct( #[StdIn] private string $stdIn = '' ) {} } ``` -------------------------------- ### Resource Method Returning 201 Created Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/CreatedResourceRenderer.md Example of a resource method that returns a 201 Created status code and includes a Location header pointing to the newly created resource. ```php return $this ->withCode(201) ->withHeader('Location', '/api/users/123'); ``` -------------------------------- ### Example Generated DI Script Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/LoggingAndCompilation.md Illustrates a generated DI script by Ray.Compiler, which optimizes dependency injection by compiling the container to PHP scripts. This eliminates runtime reflection and AOP weaving overhead. ```php // var/di/prod-app/InjectorScript.php namespace Ray\Compiler; class InjectorScript implements ScriptInjectorInterface { public function getInstance($name, $context = '') { if ($name === 'BEAR\Sunday\Extension\Application\AppInterface') { return new \MyVendor\MyApp\Module\App( new \Psr\Log\LoggerInterface(), // singleton // ... all constructor deps ); } // ... more getInstance logic } } ``` -------------------------------- ### Custom Production Module Configuration Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/AbstractAppModule.md Example of extending AbstractAppModule to configure application-specific bindings using injected app metadata like log directory. This module is intended for production environments. ```php use BEAR\Package\AbstractAppModule; use BEAR\AppMeta\AbstractAppMeta; use Ray\Di\AbstractModule; class MyAppProdModule extends AbstractAppModule { protected function configure(): void { // Use $this->appMeta to access application metadata $logDir = $this->appMeta->logDir; $this->bind('cache-dir') ->toInstance($this->appMeta->tmpDir . '/cache'); } } // Instantiation via context-based module loader $module = new MyAppProdModule($appMeta); ``` -------------------------------- ### Initialize BEAR.Package Application (Production) Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/00-Overview.md This snippet demonstrates initializing the DI container for production, including optional PSR-6 cache integration. Ensure the correct application details and cache adapter are provided. ```php $injector = Injector::getInstance( 'MyVendor\MyApp', 'prod-api-app', '/path/to/app', new FilesystemAdapter() // PSR-6 cache ); $app = $injector->getInstance(AppInterface::class); $response = $app->run($method, $uri); ``` -------------------------------- ### Query Result Caching Binding Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/LoggingAndCompilation.md Example of enabling query result caching using the @Cacheable annotation. ProdModule installs ProdQueryRepositoryModule, which enables this feature. The cache is automatically invalidated on mutation. ```php // ProdModule installs ProdQueryRepositoryModule // Enables @Cacheable annotation #[Cacheable] public function getUser(int $id): ResourceObject {} ``` -------------------------------- ### Resource Method with ReturnCreatedResource Annotation Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/CreatedResourceInterceptor.md Example of a resource method decorated with #[ReturnCreatedResource]. When this method returns a 201 status code and a Location header, the CreatedResourceInterceptor will intercept the response to render the created resource. ```php use BEAR\Package\Annotation\ReturnCreatedResource; use BEAR\Resource\ResourceObject; class UserResource extends ResourceObject { #[ReturnCreatedResource] public function onPost(string $name): static { $id = $this->create($name); return $this ->withCode(201) ->withHeader('Location', "/api/users/{$id}"); } } ``` -------------------------------- ### Initialize BEAR.Package Application (Development) Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/00-Overview.md Use this snippet to create a DI container instance for development environments. It requires the application namespace, context, and path. ```php use BEAR\Package\Injector; $injector = Injector::getInstance( 'MyVendor\MyApp', 'dev-app', '/path/to/app' ); $app = $injector->getInstance(AppInterface::class); $response = $app->run($method, $uri); ``` -------------------------------- ### Typical Usage Flow: Initialization (Development) Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/00-Overview.md Demonstrates the typical flow for initializing a BEAR.Package application in a development environment. ```APIDOC ## Typical Usage Flow: Initialization (Development) ### Initialization (Development) ```php use BEAR\Package\Injector; $injector = Injector::getInstance( 'MyVendor\MyApp', 'dev-app', '/path/to/app' ); $app = $injector->getInstance(AppInterface::class); $response = $app->run($method, $uri); ``` ``` -------------------------------- ### Typical Usage Flow: Initialization (Production) Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/00-Overview.md Illustrates the typical flow for initializing a BEAR.Package application in a production environment with PSR-6 cache. ```APIDOC ## Typical Usage Flow: Initialization (Production) ### Initialization (Production) ```php use BEAR\Package\Injector; use Laminas\Psr7\HttpFactory; use Laminas\Psr7\ServerRequest; use Psr\Http\Message\ServerRequestInterface; use Psr\Cache\CacheItemPoolInterface; use Laminas\Cache\Storage\Adapter\Filesystem; $injector = Injector::getInstance( 'MyVendor\MyApp', 'prod-api-app', '/path/to/app', new FilesystemAdapter() // PSR-6 cache ); $app = $injector->getInstance(AppInterface::class); $response = $app->run($method, $uri); ``` ``` -------------------------------- ### get Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/HttpMethodParams.md Extracts the HTTP method and parameters from the provided server, get, and post arrays. It handles method overrides and content-type negotiation. ```APIDOC ## get ### Description Extracts HTTP method and parameters from request. ### Method `get(array $server, array $get, array $post): array` ### Parameters #### Path Parameters - **server** (array) - Required - $_SERVER superglobal - **get** (array) - Required - $_GET parameters - **post** (array) - Required - $_POST parameters ### Response #### Success Response - **[0]** (string) - HTTP method (lowercase): "get", "post", "put", "patch", "delete", "head" - **[1]** (array) - Request parameters (QueryParams) ### Request Example ```php // GET request [$method, $params] = $params->get( ['REQUEST_METHOD' => 'GET'], ['id' => '1', 'name' => 'John'], [] ); // Result: ['get', ['id' => '1', 'name' => 'John']] // POST with method override [$method, $params] = $params->get( ['REQUEST_METHOD' => 'POST'], [], ['_method' => 'put', 'name' => 'Jane'] ); // Result: ['put', ['name' => 'Jane']] // JSON POST [$method, $params] = $params->get( [ 'REQUEST_METHOD' => 'POST', 'CONTENT_TYPE' => 'application/json' ], [], [] ); // Reads '{"name":"Jane"}' from php://input // Result: ['post', ['name' => 'Jane']] ``` ``` -------------------------------- ### Create ImportApp Configuration Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/ImportApp.md Instantiate ImportApp with the host, application name, and context of the application to be imported. The application directory is resolved automatically. ```php use BEAR\Package\Module\Import\ImportApp; $importApp = new ImportApp( 'user-app', 'MyVendor\UserApp', 'prod-api-app' ); // Resolve application directory automatically echo $importApp->appDir; // /path/to/user-app ``` -------------------------------- ### Custom Error Page Factory Binding Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/configuration.md Example of binding a custom error page factory in a production module. ```php class ProdModule extends AbstractAppModule { protected function configure(): void { $this->bind(ErrorPageFactoryInterface::class) ->to(CustomErrorPageFactory::class); } } ``` -------------------------------- ### Compile Application for Production Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/README.md Shows the command-line instruction to compile a BEAR.Package application for production, specifying the application name, context, and directory. ```bash ./bin/bear.compile 'MyVendor\MyApp' prod-api-app /app ``` -------------------------------- ### Core Entry Points Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/00-Overview.md Provides access to the main classes for application bootstrapping and management. ```APIDOC ## Core Entry Points This section details the primary classes for initializing and managing BEAR.Package applications. ### Injector **Purpose**: Create DI container instances. **Usage**: `Injector::getInstance($app, $context, $dir)` ### Module **Purpose**: Load context-based DI modules. **Usage**: `(new Module())($appMeta, $context)` ### Compiler **Purpose**: Compile application for production. **Usage**: `(new Compiler($app, $context, $dir))->compile()` ``` -------------------------------- ### Cacheable Annotation Usage Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Annotations.md Example of using the #[Cacheable] annotation on a method to enable result caching for query operations, integrated with QueryRepository. ```php use BEAR\RepositoryModule\Annotation\Cacheable; #[Cacheable] public function getUser(int $id): ResourceObject {} ``` -------------------------------- ### Named Annotation Usage in CliRouter Constructor Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Annotations.md Example of using the #[Named] annotation to inject the original RouterInterface implementation into the CliRouter constructor. ```php use Ray\Di\Di\Named; public function __construct( #[Named('original')] private RouterInterface $router // Original WebRouter ) {} ``` -------------------------------- ### Form-Encoded Request Body Example Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/00-Overview.md Demonstrates sending data using the `application/x-www-form-urlencoded` content type. This is a common format for submitting form data. ```php PUT /users/1 Content-Type: application/x-www-form-urlencoded name=Jane&age=31 ``` -------------------------------- ### __construct Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Compiler.md Creates a compiler instance for the given application, context, and directory. It registers a custom class loader, hooks optional compile scripts, and initializes sub-compilers. ```APIDOC ## __construct ### Description Creates a compiler instance for the given application, context, and directory. ### Method __construct ### Parameters #### Path Parameters - **appName** (string) - Required - Application namespace, e.g., "MyVendor\MyApp" - **context** (string) - Required - Context string, e.g., "prod-app" - **appDir** (string) - Required - Application root directory where `vendor/autoload.php` exists - **prepend** (bool) - Optional - Register autoloader at start of SPL stack (prepend to catch classes first) (Default: true) ### Throws - `RuntimeException` — If `{appDir}/vendor/autoload.php` does not exist ### Example ```php use BEAR\Package\Compiler; $compiler = new Compiler( 'MyVendor\MyApp', 'prod-app', '/path/to/app' ); // Compiling triggers class autoloading and tracking $report = $compiler->compile(); ``` ``` -------------------------------- ### Named Annotation Usage for Custom Router Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Annotations.md Example of using the #[Named] annotation to inject a specific named implementation of RouterInterface, such as a custom router. ```php use Ray\Di\Di\Named; #[Named('router')] private RouterInterface $customRouter; ``` -------------------------------- ### __construct Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/CliRouter.md Initializes a new instance of the CliRouter. It requires an original RouterInterface and optionally accepts Stdio for output and a path for standard input. ```APIDOC ## __construct ### Description Creates a CliRouter instance. ### Parameters #### Path Parameters - **router** (RouterInterface) - Required - Original router (WebRouter) renamed as "original" by CliModule - **stdIo** (Stdio|null) - Optional - Aura CLI stdio for output. If null, creates new CliFactory().newStdio() - **stdIn** (string) - Optional - Path to temporary file for stdin input. Created via StdIn annotation ### Example ```php use BEAR\Package\Provide\Router\CliRouter; use BEAR\Package\Provide\Router\WebRouter; $webRouter = new WebRouter('http://localhost', new HttpMethodParams()); $cliRouter = new CliRouter($webRouter); ``` ``` -------------------------------- ### Compile BEAR.Package Application Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/00-Overview.md Use the Compiler class to prepare your application for production. This generates essential files like preload scripts and dependency injection graphs. ```php use BEAR\Package\Compiler; $compiler = new Compiler('MyVendor\MyApp', 'prod-api-app', '/path/to/app'); $report = $compiler->compile(); // Generated files: // - /path/to/app/preload.php // - /path/to/app/var/di/prod-api-app/... // - /path/to/app/var/di/prod-api-app/Graph.dot ``` -------------------------------- ### Define a Custom Annotation Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Annotations.md Define a custom annotation class using PHP attributes. This example creates a 'CacheableResource' annotation with a configurable time-to-live (ttl). ```php namespace MyVendor\MyApp\Annotation; use Attribute; #[Attribute(Attribute::TARGET_CLASS)] final class CacheableResource { public function __construct(public int $ttl = 3600) {} } ``` -------------------------------- ### Typical Usage Flow: Compilation Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/00-Overview.md Shows the process of compiling a BEAR.Package application for production deployment. ```APIDOC ## Typical Usage Flow: Compilation ### Compilation ```php use BEAR\Package\Compiler; $compiler = new Compiler('MyVendor\MyApp', 'prod-api-app', '/path/to/app'); $report = $compiler->compile(); // Generated files: // - /path/to/app/preload.php // - /path/to/app/var/di/prod-api-app/... // - /path/to/app/var/di/prod-api-app/Graph.dot ``` ``` -------------------------------- ### Instantiate HttpMethodParams Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/HttpMethodParams.md Create a new instance of HttpMethodParams. Specify the path to the stdin stream if not using the default 'php://input'. ```php use BEAR\Package\Provide\Router\HttpMethodParams; $params = new HttpMethodParams('php://input'); ``` -------------------------------- ### Context Configuration Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/00-Overview.md Details the core framework modules and context-specific configurations. ```APIDOC ## Context Configuration This section outlines the modules used for configuring application contexts. ### PackageModule **Purpose**: Core framework module. **Activation**: Always loaded first. ### ProdModule **Purpose**: Production bindings (caching, compilation). **Activation**: context contains "prod". ### ApiModule **Purpose**: API mode (app://self scheme). **Activation**: context contains "api". ### CliModule **Purpose**: CLI mode (argument parsing, stdout output). **Activation**: context contains "cli". ### HalModule **Purpose**: HAL+JSON rendering. **Activation**: context contains "hal". ``` -------------------------------- ### Dependency Injection Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/00-Overview.md Explains the classes related to dependency injection and module loading. ```APIDOC ## Dependency Injection This section describes the components that facilitate dependency injection within BEAR.Package. ### PackageInjector **Purpose**: Internal injector factory with caching. **Role**: Injector facade backend. ### AbstractAppModule **Purpose**: Base for app context modules. **Role**: App-specific configuration. ### AppMetaModule **Purpose**: Provide app metadata and bindings. **Role**: AppInterface binding. ### ResourceObjectModule **Purpose**: Bind all resource classes. **Role**: Automatic resource discovery. ``` -------------------------------- ### match Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/CliRouter.md Routes a CLI request to a resource URI by parsing command-line arguments and delegating to the wrapped router. ```APIDOC ## match ### Description Routes CLI request to a resource URI. ### Method `public function match(array $globals, array $server): RouterMatch` ### Parameters #### Path Parameters - **globals** (array) - PHP superglobals (not used in CLI routing) - **server** (array) - $\_SERVER-like array with argc, argv ### Return Type `RouterMatch` — Routed resource URI ### CLI Format ``` php index.php {method} {uri} [params...] ``` ### Examples ```bash php index.php get /users php index.php get '/users?id=1' php index.php post /users name=John age=30 php index.php put /users/1 name=Jane php index.php delete /users/1 ``` ### Example ```php $match = $cliRouter->match( [], [ 'argc' => 4, 'argv' => ['index.php', 'get', '/users', 'id=1'] ] ); echo $match->method; // "get" echo $match->path; // "http://localhost/users" (combined with router's schemeHost) print_r($match->query); // ['id' => '1'] ``` ### Throws - `InvalidCliSapiException` — If not running under CLI SAPI ``` -------------------------------- ### Get Cached or New Injector Instance Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/PackageInjector.md Use getInstance to retrieve a cached injector or create a new one. It supports PSR-6 caching for compiled injectors in production. ```php use BEAR\Package\Injector\PackageInjector; use BEAR\AppMeta\Meta; use Symfony\Component\Cache\Adapter\FilesystemAdapter; $meta = new Meta('MyVendor\MyApp', 'prod-app', '/path/to/app'); $cache = new FilesystemAdapter(); $injector = PackageInjector::getInstance($meta, 'prod-app', $cache); $app = $injector->getInstance(AppInterface::class); ``` -------------------------------- ### Get Injector Instance with Default Caching Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Injector.md Use getInstance to retrieve a cached or new InjectorInterface. It requires application name, context, and directory. Defaults to an in-memory cache. ```php use BEAR\Package\Injector; use Ray\Di\InjectorInterface; // Get injector with default caching $injector = Injector::getInstance( 'MyVendor\MyApp', 'prod-api-app', '/path/to/app' ); // Retrieve a bound instance from container $app = $injector->getInstance(AppInterface::class); ``` -------------------------------- ### Instantiate WebRouter Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/WebRouter.md Creates a new WebRouter instance. Requires a schemeHost string and an HttpMethodParamsInterface implementation. ```php use BEAR\Package\Provide\Router\WebRouter; use BEAR\Package\Provide\Router\HttpMethodParams; $router = new WebRouter( 'http://localhost', new HttpMethodParams() ); ``` -------------------------------- ### render Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/CreatedResourceRenderer.md Renders the 201 Created resource by fetching the created resource via the Location header and outputting it as HAL+JSON. ```APIDOC ## render ### Description Renders the 201 Created resource. This method extracts the scheme/host from the original resource URI, combines it with the Location header value to create a full URI, fetches the created resource using the ResourceInterface, updates headers (content-type to application/hal+json), and returns the created resource as a string. ### Method `render` ### Endpoint N/A (This is a method call, not an HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **ro** (ResourceObject) - Required - 201 response with Location header ### Return Type `string` — HAL+JSON body of created resource ### Process 1. Extracts scheme/host from original resource URI 2. Combines with Location header value to create full URI 3. Fetches created resource via ResourceInterface 4. Updates headers (content-type = application/hal+json) 5. Returns created resource as string ### Headers Updated - `content-type` → `application/hal+json` - `Location` → Result of reverse routing (for compatibility with routers) ### Throws - `LocationHeaderRequestException` — If created resource fetch fails ### Example Resource method returns: ```php return $this ->withCode(201) ->withHeader('Location', '/api/users/123'); ``` Renderer: 1. Fetches `app://self/api/users/123` (or http equivalent) 2. Converts to HAL+JSON: `{"name":"John","_links":{"self":{...}}}` 3. Updates Location header if router can reverse it ``` -------------------------------- ### Optional .compile.php Hook Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/LoggingAndCompilation.md An example of an optional .compile.php hook file. This file is executed during Compiler construction and can be used to define null or stub objects needed for compilation. ```php // {appDir}/.compile.php // Executed during Compiler construction class NullUser extends User { // Define null object for compilation } class NullPost extends Post { } ``` -------------------------------- ### Get Injector Instance with Custom Cache Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Injector.md Use getInstance with a custom PSR-6 cache adapter for storing compiled injectors. This allows for persistent caching across application runs. ```php use BEAR\Package\Injector; use Ray\Di\InjectorInterface; use Symfony\Component\Cache\Adapter\FilesystemAdapter; // With custom cache $cache = new FilesystemAdapter(); $injector = Injector::getInstance( 'MyVendor\MyApp', 'dev-app', '/path/to/app', $cache ); ``` -------------------------------- ### Run Tests Source: https://github.com/bearsunday/bear.package/blob/1.x/demo/README.md Execute the project's automated tests using PHPUnit. ```bash ./vendor/bin/phpunit ``` -------------------------------- ### Bind Interceptors with Custom Annotations Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Annotations.md Bind interceptors to methods annotated with a custom annotation. This example shows how to bind the 'CacheInterceptor' to classes annotated with 'CacheableResource' using an application module. ```php use BEAR\Package\AbstractAppModule; class CacheModule extends AbstractAppModule { protected function configure(): void { $this->bindInterceptor( $this->matcher->annotatedWith(CacheableResource::class), $this->matcher->any(), [CacheInterceptor::class] ); } } ``` -------------------------------- ### Compile BEAR.Sunday Application Source: https://github.com/bearsunday/bear.package/blob/1.x/CLAUDE.md Compile a BEAR.Sunday application for a specific context and path. ```bash # Compile a BEAR.Sunday application ./bin/bear.compile 'VendorName\AppName' context-name /path/to/app # Example (used in tests) composer compile ``` -------------------------------- ### WebRouter::__construct Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/WebRouter.md Creates a WebRouter instance. It requires the scheme and host, and an HttpMethodParamsInterface for extracting HTTP method and parameters. ```APIDOC ## WebRouter::__construct ### Description Creates a WebRouter instance. ### Method __construct ### Parameters #### Path Parameters - **schemeHost** (string) - Injected - Scheme and host, e.g., "http://localhost" or "app://self" (from DefaultSchemeHost binding) - **httpMethodParams** (HttpMethodParamsInterface) - Injected - Service for extracting HTTP method and parameters from $\_SERVER, $\_GET, $\_POST ### Request Example ```php use BEAR\Package\Provide\Router\WebRouter; use BEAR\Package\Provide\Router\HttpMethodParams; $router = new WebRouter( 'http://localhost', new HttpMethodParams() ); ``` ``` -------------------------------- ### Get Override Injector Instance for Testing Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Injector.md Use getOverrideInstance to create a new injector with an additional module to override or extend bindings. This is primarily used for testing purposes, such as mocking dependencies. ```php use BEAR\Package\Injector; use Ray\Di\AbstractModule; use Psr\Log\LoggerInterface; class TestLoggerModule extends AbstractModule { protected function configure(): void { $this->bind(LoggerInterface::class) ->to(NullLogger::class); } } // Create injector for testing with mocked logger $injector = Injector::getOverrideInstance( 'MyVendor\MyApp', 'dev-app', '/path/to/app', new TestLoggerModule() ); ``` -------------------------------- ### Run Console Application Source: https://github.com/bearsunday/bear.package/blob/1.x/demo/README.md Execute PHP scripts from the command line to interact with the application. Specify the HTTP method, path, and optional query parameters. ```bash php public/index.php get / php public/index.php get '/user?id=1' CONTEXT=prod-hal-app php public/index.php get / ``` -------------------------------- ### __invoke Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Module.md Returns a configured Ray.Di module based on application metadata and a context string. It loads modules in reverse order of the context segments, allowing later modules to override earlier ones. ```APIDOC ## __invoke ### Description Returns a configured Ray.Di module based on application metadata and context string. It loads modules in reverse order of the context segments, allowing later modules to override earlier ones. ### Method `__invoke` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **appMeta** (AbstractAppMeta) - Required - Application metadata from `BEAR AppMeta Meta`, containing app name, context, and directory. - **context** (string) - Required - Hyphenated context string, e.g., `"prod-api-app"`. Each segment (right-to-left) maps to a module class. ### Request Example ```php use BEAR\Package\Module; use BEAR\AppMeta\Meta; $module = new Module(); $appMeta = new Meta('MyVendor\MyApp', 'prod-api-app', '/path/to/app'); $configured = $module($appMeta, 'prod-api-app'); ``` ### Response #### Success Response (200) - **AbstractModule** (Ray\Di\AbstractModule) - Configured DI module with all context modules installed. #### Response Example ```php // The returned object is an instance of Ray\Di\AbstractModule // Example of how it might be used: // $diContainer = $configured->getDIContainer(); ``` ### Throws - `InvalidContextException` — If a context module cannot be resolved or does not extend AbstractModule ``` -------------------------------- ### Instantiate CliRouter Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/CliRouter.md Create a new CliRouter instance, wrapping an existing RouterInterface. Optionally provide Stdio for output and a path for stdin. ```php use BEAR\Package\Provide\Router\CliRouter; use BEAR\Package\Provide\Router\WebRouter; $webRouter = new WebRouter('http://localhost', new HttpMethodParams()); $cliRouter = new CliRouter($webRouter); ``` -------------------------------- ### Run All Tests Source: https://github.com/bearsunday/bear.package/blob/1.x/CLAUDE.md Execute all tests in the project using Composer or directly with PHPUnit. ```bash # Run all tests composer test # Or directly ./vendor/bin/phpunit ``` -------------------------------- ### Execute CLI Commands with BEAR.Package Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/00-Overview.md This snippet shows how to interact with your BEAR.Package application via the command line. Ensure the 'cli' context is enabled for these commands to function correctly. ```bash # Requires 'cli' context php public/index.php get /users php public/index.php post /users name=John php public/index.php put /users/1 name=Jane php public/index.php delete /users/1 ``` -------------------------------- ### Run All Quality Checks Source: https://github.com/bearsunday/bear.package/blob/1.x/CLAUDE.md Execute all code quality checks, including style and static analysis. ```bash # Run all quality checks composer tests ``` -------------------------------- ### ReturnCreatedResource Annotation Usage in Resource Method Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Annotations.md Example of using the #[ReturnCreatedResource] annotation on a POST method to automatically fetch and render the created resource as HAL+JSON when a 201 Created response with a Location header is returned. ```php use BEAR\Package\Annotation\ReturnCreatedResource; use BEAR\Resource\ResourceObject; class UserResource extends ResourceObject { #[ReturnCreatedResource] public function onPost(string $name, int $age): static { $id = $this->db->insert('users', ['name' => $name, 'age' => $age]); return $this ->withCode(201) ->withHeader('Location', "/api/users/{$id}"); } } ``` -------------------------------- ### Get Module Cached Application Instance Source: https://github.com/bearsunday/bear.package/wiki/get-app-in-legacy-way Retrieves a cached application instance using its module. It supports APC or filesystem caching based on availability and the provided temporary directory. This method is useful for scenarios where application modules need to be cached for performance. ```php /** * @param string $appName * @param string $context * @param string $tmpDir * @param Cache $cache * * @return \BEAR\Sunday\Extension\Application\AppInterface */ public static function getModuleCachedApp($appName, $context, $tmpDir, Cache $cache = null) { $appModule = $appName . '\Module\AppModule'; $cache = $cache ?: (function_exists('apc_fetch') ? new ApcCache : new FilesystemCache($tmpDir)); $cacheKey = 'module-' . $appName . $context; $moduleProvider = function () use ($appModule, $context) {return new $appModule($context);}; $injector = ModuleCacheInjector::create($moduleProvider, $cache, $cacheKey, $tmpDir); $app = $injector->getInstance('BEAR\Sunday\Extension\Application\AppInterface'); /** $app \BEAR\Sunday\Extension\Application\AppInterface */ return $app; } ``` -------------------------------- ### Provide Writable Cache Directory Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/Utilities.md Ensures that a specified cache directory exists and is writable, creating it if necessary. Throws an exception if the directory cannot be created or written to. ```php namespace BEAR\Package\Provide\Cache; final class CacheDirProvider implements ProviderInterface { public function __construct(AbstractAppMeta $appMeta) {} public function get(): string } ``` ```php $cacheDir = (new CacheDirProvider($appMeta))->get(); // Result: "/app/var/tmp/cache" ``` -------------------------------- ### __construct Source: https://github.com/bearsunday/bear.package/blob/1.x/_autodocs/api-reference/CliResponder.md Creates a CLI responder instance, injecting necessary dependencies for header formatting and conditional response handling. ```APIDOC ## __construct ### Description Creates a CLI responder instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Parameters - **header** (HeaderInterface) - Required - Header formatter for CLI output - **condResponse** (ConditionalResponseInterface) - Required - Conditional response handler (304 Not Modified) ### Bindings Automatically injected via CliModule ### Example ```php use BEAR.Package\Provide\Transfer\CliResponder; // Injected via DI container in CLI context $responder = $injector->getInstance(TransferInterface::class); ``` ```