### Installer Output Example Source: https://github.com/spiral/docs/blob/3.16/docs/en/start/installation.md This is an example of the output you will see during the Spiral application installation process, including prompts for selecting an application preset. ```output Creating a "spiral/app" project at "./my-app"\nInstalling spiral/app (1.1.1)\n - Installing spiral/app (1.1.1): Extracting archive\nCreated project in /var/www/my-app\n> Installer\Installer::install\n\n Which application preset do you want to install?\n [1] Web\n [2] Cli\n [3] gRPC\n Make your selection (1): ``` -------------------------------- ### Start Temporal Development Server Source: https://github.com/spiral/docs/blob/3.16/docs/en/temporal/configuration.md Start a local Temporal development server using the Temporal CLI. Ensure the CLI is installed first. ```bash temporal server start-dev ``` -------------------------------- ### Initialize Deployer Configuration Source: https://github.com/spiral/docs/blob/3.16/docs/en/start/deployment.md Run this command to start the interactive setup for your deployment recipe. It will generate a deploy.php or deploy.yaml file. ```bash ./vendor/bin/dep init ``` -------------------------------- ### Example API Request for Products Source: https://github.com/spiral/docs/blob/3.16/docs/en/data-grid/getting-started.md Demonstrates a GET request with query parameters for filtering, sorting, and pagination of products. ```http GET: /api/products?filter[min_price]=50&filter[max_price]=200&filter[category]=Electronics&sort[popularity]=desc&paginate[page]=2&paginate[limit]=20 ``` -------------------------------- ### Install Golang gRPC Dependencies Source: https://github.com/spiral/docs/blob/3.16/docs/en/grpc/client.md Install the necessary gRPC and protobuf dependencies for Golang using the go get command. ```bash go get -u google.golang.org/grpc go get -u github.com/golang/protobuf/protoc-gen-go ``` -------------------------------- ### Install gRPC Client Package Source: https://github.com/spiral/docs/blob/3.16/resources/releases/grpc-client/1.0.md Install the gRPC client package using Composer. Ensure the gRPC extension is installed. ```bash composer require spiral/grpc-client -W ``` -------------------------------- ### Install spiral/storage Component Source: https://github.com/spiral/docs/blob/3.16/docs/en/advanced/storage.md Install the spiral/storage component using Composer. ```bash composer require spiral/storage ``` -------------------------------- ### PHP Code Example with File Path Source: https://github.com/spiral/docs/blob/3.16/resources/guidelines/how-to-write-documentation.md Include file paths as comments above code blocks for PHP examples. ```php ```php app/src/Application/Kernel.php // Code for Kernel.php would go here ``` ``` -------------------------------- ### Controller for Routing Examples Source: https://github.com/spiral/docs/blob/3.16/docs/en/http/routing.md Example controller with methods to be targeted by routes. Demonstrates basic action methods and parameter handling. ```php namespace App\Controller; class HomeController { public function index(): string { return 'index'; } public function other(): string { return 'other'; } public function user(int $id): string { return "hello {$id}"; } } ``` -------------------------------- ### Example HTTP Configuration File Source: https://github.com/spiral/docs/blob/3.16/docs/en/testing/start.md An example of a typical HTTP configuration file used within the application. ```php return [ 'basePath' => '/', 'headers' => [ 'Content-Type' => 'text/html; charset=UTF-8', ], 'middleware' => [], ]; ``` -------------------------------- ### Restart Installation Source: https://github.com/spiral/docs/blob/3.16/docs/en/start/installation.md If the installation process encounters an error, you can restart it by running 'composer install' in the project directory. ```bash composer install ``` -------------------------------- ### Install Discoverer Package Source: https://github.com/spiral/docs/blob/3.16/docs/en/component/discoverer.md Install the discoverer package using Composer. ```terminal composer require spiral-packages/discoverer ``` -------------------------------- ### Install swagger-php Package Source: https://github.com/spiral/docs/blob/3.16/docs/en/http/openapi.md Install the swagger-php package using Composer. ```bash composer require spiral-packages/swagger-php ``` -------------------------------- ### Start Symfony VarDumper Server Source: https://github.com/spiral/docs/blob/3.16/docs/en/basics/debug.md Run this command in your terminal to start the standalone server that collects dumped data. ```bash ./vendor/bin/var-dump-server ``` -------------------------------- ### Install Spiral Application Bundle Source: https://github.com/spiral/docs/blob/3.16/docs/en/cookbook/simple-queue-system.md Installs the default spiral/app bundle, which includes most required components for building a producer application. ```bash composer create-project spiral/app my-app ``` -------------------------------- ### Install aws/aws-sdk-php Source: https://github.com/spiral/docs/blob/3.16/docs/en/advanced/storage.md Install the AWS SDK for PHP using Composer to enable CloudFront integration. ```terminal composer require aws/aws-sdk-php ^3.0 ``` -------------------------------- ### Initialize Kernel and Run Application Source: https://github.com/spiral/docs/blob/3.16/docs/en/framework/kernel.md Initialize the kernel using the static `create` method and run the application. This example also demonstrates disabling the error handler and dumping directory information. ```php $myapp = MyApp::create( directories: [ 'root' => __DIR__, ], handleErrors: false // do not mount error handler ); $myapp->run(environment: null); // use default env \dump($myapp->get(\Spiral\Boot\DirectoriesInterface::class)->getAll()); ``` -------------------------------- ### #[InitMethod] Example in DatabaseBootloader Source: https://github.com/spiral/docs/blob/3.16/docs/en/framework/bootloaders.md Demonstrates how to use #[InitMethod] with different priorities to register database drivers and connections during the initialization phase. Higher priority values execute earlier. ```php use Spiral\Boot\Attribute\InitMethod; final class DatabaseBootloader extends Bootloader { // Critical: runs first #[InitMethod(priority: 10)] public function registerDrivers(DatabaseManager $manager): void { $manager->addDriver('mysql', MySQLDriver::class); $manager->addDriver('postgres', PostgresDriver::class); } // Normal: runs after high priority #[InitMethod] public function registerConnections(Container $container): void { $container->bindSingleton( ConnectionInterface::class, DefaultConnection::class ); } // Low priority: runs last #[InitMethod(priority: -10)] public function registerExtensions(): void { // Optional extensions that depend on core setup } } ``` -------------------------------- ### Get Session ID (when started) Source: https://github.com/spiral/docs/blob/3.16/docs/en/basics/session.md Retrieve the current session ID. This method is only valid when the session has been resumed or started. ```php dump($this->session->getID()); ``` -------------------------------- ### Demo Controller Example Source: https://github.com/spiral/docs/blob/3.16/docs/en/http/routing.md A controller generated via scaffolding, containing a 'test' action. This serves as an example target for HTTP routes. ```php namespace App\Controller; class DemoController { public function test(): string { return 'demo test'; } } ``` -------------------------------- ### Install S3 Flysystem Packages Source: https://github.com/spiral/docs/blob/3.16/docs/en/advanced/storage.md Install either the league/flysystem-aws-s3-v3 or league/flysystem-async-aws-s3 package using Composer to interact with S3 servers. ```bash composer require league/flysystem-aws-s3-v3 ^2.0 // OR composer require league/flysystem-async-aws-s3 ^2.0 ``` -------------------------------- ### Create Files at Different Storage Levels Source: https://github.com/spiral/docs/blob/3.16/docs/en/advanced/storage.md Demonstrates creating a file named 'example.txt' using the Storage, Bucket, and File interfaces. Each level requires different argument formats for specifying the file. ```php use Spiral\Storage\StorageInterface; class UploadController { public function createFile(StorageInterface $storage): array { $result = []; // 1. Storage level $result[] = $storage->create('bucket://example.txt'); // 2. Bucket level $result[] = $storage->bucket('bucket') ->create('example.txt'); // 3. File level $result[] = $storage->bucket('bucket') ->file('example.txt') ->create(); return $result; } } ``` -------------------------------- ### Install otel-bridge and exporter Source: https://github.com/spiral/docs/blob/3.16/docs/en/advanced/telemetry.md Use composer to install the necessary packages for OpenTelemetry integration. The exporter-otlp is used here as an example; other exporters can be used as per OpenTelemetry documentation. ```bash composer require spiral/otel-bridge open-telemetry/exporter-otlp ``` -------------------------------- ### Simple Feature Test Example Source: https://github.com/spiral/docs/blob/3.16/docs/en/testing/start.md Feature tests should extend `Tests\TestCase` to bootstrap the application. This example demonstrates testing an HTTP GET request and asserting a 'NotFound' response. ```php namespace Tests\Feature\Controller\UserController; use Tests\TestCase; final class ShowActionTest extends TestCase { public function testShowPageNotFoundIfUserNotExist(): void { $http = $this->fakeHttp(); $response = $http->get('/user/1'); $response->assertNotFound(); } } ``` -------------------------------- ### Example PingSite Job Handler Source: https://github.com/spiral/docs/blob/3.16/docs/en/start/queue-basics.md Implement the logic for your background job within the `invoke` method. This example sends a GET request to a specified site using an injected HttpClientInterface. ```php namespace App\Endpoint\Job; use Spiral\Queue\JobHandler; final class PingSiteJob extends JobHandler { public function invoke(HttpClientInterface $client, string $site): void { $response = $client->request('GET', $site); // do something with response ... } } ``` -------------------------------- ### Serve Application with Custom Config Source: https://github.com/spiral/docs/blob/3.16/docs/en/cookbook/quick-start.md You can start the application server using an alternative configuration file by specifying it with the -c flag. ```bash ./rr serve -c .rr.dev.yaml ``` -------------------------------- ### Provision Server with Deployer Source: https://github.com/spiral/docs/blob/3.16/docs/en/start/deployment.md Use this command to provision your server. Override the default remote user if necessary (e.g., 'root') to perform initial setup, including creating the deployer user and configuring the website. ```bash dep provision -o remote_user=root ``` -------------------------------- ### Execute Bootloader Logic with boot() Method Source: https://github.com/spiral/docs/blob/3.16/docs/en/framework/bootloaders.md The `boot()` method runs after all `init()` methods complete. Use it to configure services with finalized configuration, register routes, middleware, or event listeners. ```php namespace Spiral\Tests\Application\Bootloader; use Spiral\Boot\Bootloader; final class GithubClientBootloader extends Bootloader { public function boot( GithubConfig $config, HttpBootloader $http ): void { // Configuration is now compiled and ready $client = new GithubClient($config->getAccessToken()); // Other bootloaders are initialized $http->addMiddleware(GithubAuthMiddleware::class); } } ``` -------------------------------- ### #[BootMethod] Example in ApplicationBootloader Source: https://github.com/spiral/docs/blob/3.16/docs/en/framework/bootloaders.md Illustrates the use of #[BootMethod] with varying priorities to configure error handling, routes, and event listeners during the application's boot phase. Methods with higher priority run first. ```php use Spiral\Boot\Attribute\BootMethod; final class ApplicationBootloader extends Bootloader { // Critical services first #[BootMethod(priority: 10)] public function configureErrorHandling(ErrorHandler $handler): void { $handler->addRenderer(new JsonErrorRenderer()); } // Standard configuration #[BootMethod] public function configureRoutes(RouterInterface $router): void { $router->addRoute('home', new Route('/', HomeController::class)); } // Non-critical features last #[BootMethod(priority: -10)] public function registerEventListeners( EventDispatcherInterface $dispatcher ): void { $dispatcher->addListener( ApplicationStarted::class, fn() => $this->onStart() ); } } ``` -------------------------------- ### Install and Serve Spiral Application Source: https://context7.com/spiral/docs/llms.txt Use Composer to create a new Spiral project and then start the RoadRunner application server. The application will be accessible at http://localhost:8080. ```bash # Create a new project (interactive installer lets you pick Web, CLI, or gRPC preset) composer create-project spiral/app my-app # Start the RoadRunner application server (Linux) cd my-app ./rr serve # Application is now available at http://localhost:8080 ``` -------------------------------- ### Basic Grid Schema Setup Source: https://github.com/spiral/docs/blob/3.16/docs/en/data-grid/grid-schema.md Demonstrates the basic structure of a Grid Schema, including setting pagination, adding a sorter, and defining a filter. ```php use Spiral\DataGrid\GridSchema; use Spiral\DataGrid\Specification\Filter\Like; use Spiral\DataGrid\Specification\Pagination\PagePaginator; use Spiral\DataGrid\Specification\Sorter\Sorter; use Spiral\DataGrid\Specification\Value\StringValue; $schema = new GridSchema(); // User pagination: limit results to 10 per page $schema->setPaginator(new PagePaginator(10)); // Sorting option: by id $schema->addSorter('id', new Sorter('id')); // Filter option: find by name matching user input $schema->addFilter('name', new Like('name', new StringValue())); ``` -------------------------------- ### Resume and Get Session ID Source: https://github.com/spiral/docs/blob/3.16/docs/en/basics/session.md Manually resume or create a session and retrieve its ID. The session is automatically started on first data access and committed when the request leaves `SessionMiddleware`. ```php use Spiral\Session\SessionInterface; // ... public function index(SessionInterface $session): void { $session->resume(); dump($session->getID()); } ``` -------------------------------- ### JavaScript Centrifuge RPC Client Source: https://github.com/spiral/docs/blob/3.16/docs/en/websockets/services.md Example of using the Centrifuge JavaScript SDK to make RPC calls. Demonstrates making POST and GET requests with different data payloads. ```javascript import {Centrifuge} from 'centrifuge'; const centrifuge = new Centrifuge('http://127.0.0.18000/connection/websocket'); // Post request centrifuge.rpc("post:news/store", {"title": "News title"}).then(function (res) { console.log('rpc result', res); }, function (err) { console.error('rpc error', err); }); // Get request with query params centrifuge.rpc("get:news/123", {"lang": "en"}).then(function (res) { console.log('rpc result', res); }, function (err) { console.error('rpc error', err); }); ``` -------------------------------- ### Basic Controller Test with FakeHttp Source: https://github.com/spiral/docs/blob/3.16/docs/en/testing/http.md This example demonstrates a basic test for a HomeController using FakeHttp. It sends a GET request to the root endpoint and asserts that the response status is OK. ```php namespace Tests\Feature; use Spiral\Testing\Http\FakeHttp; use Tests\TestCase; final class HomeControllerTest extends TestCase { private FakeHttp $http; protected function setUp(): void { parent::setUp(); $this->http = $this->fakeHttp(); } public function testIndex(): void { $response = $this->http->get('/'); $response->assertOk(); } } ``` -------------------------------- ### HttpInput Implementation Example Source: https://github.com/spiral/docs/blob/3.16/docs/en/data-grid/input.md An example implementation of `InputInterface` for HTTP requests, adapting the framework's request object to the Data Grid input contract. ```php // Example HTTP Input implementation (framework-specific) class HttpInput implements InputInterface { public function __construct(private readonly RequestInterface $request) {} public function hasValue(string $option): bool { return $this->request->has($option); } public function getValue(string $option, mixed $default = null): mixed { return $this->request->get($option, $default); } public function withNamespace(string $namespace): InputInterface { return new self($this->request->withPrefix($namespace)); } } ``` -------------------------------- ### Bind ValidationInterface in Bootloader Source: https://github.com/spiral/docs/blob/3.16/docs/en/cookbook/migration-from-v2.md After installing a validator, bind the ValidationInterface with your chosen implementation in your application's bootloader. This example shows how to initialize validation using Spiral's validation provider. ```php use Spiral\Validation\ValidationInterface; use Spiral\Validation\ValidationProviderInterface; use Spiral\Validator\FilterDefinition; class AppBootloader extends Bootloader { protected const SINGLETONS = [ ValidationInterface::class => [self::class, 'initValidation'], ]; // ... public function initValidation(ValidationProviderInterface $provider): ValidationInterface { return $provider->getValidation(FilterDefinition::class); } } ``` -------------------------------- ### Build Frontend Source: https://github.com/spiral/docs/blob/3.16/docs/en/cookbook/simple-chat.md Navigate to the frontend directory and run the build command to create the frontend.js file. ```terminal cd ./frontend npm run build ``` -------------------------------- ### Vue Project Configuration Answers Source: https://github.com/spiral/docs/blob/3.16/docs/en/cookbook/simple-chat.md Example answers provided during the Vue.js project initialization. ```terminal ✔ Project name: … frontend ✔ Add TypeScript? … No ✔ Add JSX Support? … No ✔ Add Vue Router for Single Page Application development? … No ✔ Add Pinia for state management? … No ✔ Add Vitest for Unit testing? … No ✔ Add Cypress for both Unit and End-to-End testing? … No ✔ Add ESLint for code quality? … No ✔ Add Prettier for code formatting? … No Scaffolding project in ./frontend... Done. ``` -------------------------------- ### Read Constant Attributes Source: https://github.com/spiral/docs/blob/3.16/docs/en/advanced/attributes.md Access attributes defined on class constants (PHP 8.0+). This example shows how to retrieve all attributes for a constant and how to get a specific attribute instance, including accessing its properties. ```php use App\Metadata\Deprecated; class StatusCodes { #[Deprecated(since: '2.0', alternative: 'STATUS_ACTIVE')] public const STATUS_OK = 1; public const STATUS_ACTIVE = 1; } $reflection = new \ReflectionClassConstant(StatusCodes::class, 'STATUS_OK'); // Get all constant attributes $attributes = $reader->getConstantMetadata($reflection); // Get first matching attribute $deprecated = $reader->firstConstantMetadata($reflection, Deprecated::class); if ($deprecated !== null) { echo $deprecated->getSince(); // 2.0 echo $deprecated->getAlternative(); // STATUS_ACTIVE } ``` -------------------------------- ### Read Function Attributes Source: https://github.com/spiral/docs/blob/3.16/docs/en/advanced/attributes.md Retrieve attributes from methods and functions for purposes like behavior configuration or route registration. This example demonstrates getting all attributes, filtering by type, and fetching a single instance. ```php use Spiral\Router\Annotation\Route; $reflection = new \ReflectionMethod(UserController::class, 'list'); // Get all method attributes $attributes = $reader->getFunctionMetadata($reflection); // Get specific attribute type $routes = $reader->getFunctionMetadata($reflection, Route::class); // Get first matching attribute $route = $reader->firstFunctionMetadata($reflection, Route::class); if ($route !== null) { echo $route->getPath(); // /users var_dump($route->getMethods()); // ['GET'] } ``` -------------------------------- ### Initialize and Run Application in Spiral v3 Source: https://github.com/spiral/docs/blob/3.16/docs/en/cookbook/migration-from-v2.md Use the `create` method on `Spiral\Boot\AbstractKernel` for application initialization, replacing the removed `init` method. ```php App::create( directories: ['root' => __DIR__] )->run(); ``` -------------------------------- ### Read Property Attributes Source: https://github.com/spiral/docs/blob/3.16/docs/en/advanced/attributes.md Access attributes defined on class properties to configure their behavior, such as database column mapping. This example shows how to get all attributes, filter by type, and retrieve a single instance. ```php use Cycle\Annotated\Annotation\Column; $reflection = new \ReflectionProperty(User::class, 'email'); // Get all property attributes $attributes = $reader->getPropertyMetadata($reflection); // Get specific attribute type $columns = $reader->getPropertyMetadata($reflection, Column::class); // Get first matching attribute $column = $reader->firstPropertyMetadata($reflection, Column::class); if ($column !== null) { echo $column->getType(); // string var_dump($column->isNullable()); // false } ``` -------------------------------- ### Initialize Bootloader with init() Method Source: https://github.com/spiral/docs/blob/3.16/docs/en/framework/bootloaders.md The `init()` method runs before any bootloader's `boot()` method. Use it to set configuration defaults, register container bindings, or initialize services needed by other bootloaders. ```php namespace Spiral\Tests\Application\Bootloader; use Spiral\Boot\Bootloader; use Spiral\Config\ConfiguratorInterface; use Spiral\Core\EnvironmentInterface; final class GithubClientBootloader extends Bootloader { public function __construct( private readonly ConfiguratorInterface $config ) {} public function init(EnvironmentInterface $env): void { // Set defaults before configuration is accessed $this->config->setDefaults(GithubConfig::CONFIG, [ 'access_token' => $env->get('GITHUB_ACCESS_TOKEN'), 'secret' => $env->get('GITHUB_SECRET'), 'timeout' => 30, ]); } } ``` -------------------------------- ### Use PSR-16 CacheInterface (PHP) Source: https://context7.com/spiral/docs/llms.txt Demonstrates injecting and using the PSR-16 `CacheInterface` for default cache storage and accessing named storages via `CacheStorageProviderInterface`. Includes methods for getting, setting, and deleting cache items, with an example of setting multiple items. ```php // Usage — inject PSR-16 CacheInterface for default storage use Psr\SimpleCache\CacheInterface; use Spiral\Cache\CacheStorageProviderInterface; class UserProfileService { private readonly CacheInterface $userCache; public function __construct( CacheInterface $cache, // default storage CacheStorageProviderInterface $provider // named storage access ) { $this->userCache = $provider->storage('user-data'); // alias → rr-redis with prefix } public function getProfile(int $userId): array { $key = "profile:{$userId}"; if ($this->userCache->has($key)) { return $this->userCache->get($key); } $profile = $this->fetchFromDatabase($userId); // Store with 1-hour TTL $this->userCache->set($key, $profile, ttl: 3600); return $profile; } public function invalidate(int $userId): void { $this->userCache->delete("profile:{$userId}"); } public function warmup(array $userIds): void { $profiles = array_combine( array_map(fn($id) => "profile:{$id}", $userIds), array_map(fn($id) => $this->fetchFromDatabase($id), $userIds) ); $this->userCache->setMultiple($profiles, ttl: 3600); } } ``` -------------------------------- ### Execute Console Command with Options Source: https://github.com/spiral/docs/blob/3.16/docs/en/cookbook/console-validation.md Example of how to run the defined console command with arguments and options from the terminal. ```terminal php app.php user:register john_smith john@site.com -as ``` -------------------------------- ### Install RoadRunner CLI with Composer Source: https://github.com/spiral/docs/blob/3.16/docs/en/start/server.md Use Composer to install the `spiral/roadrunner-cli` package to manage RoadRunner installations. ```bash composer require spiral/roadrunner-cli ``` -------------------------------- ### Install spiral/filters-bridge Source: https://github.com/spiral/docs/blob/3.16/docs/en/filters/bridge.md Install the filters-bridge package using composer. This will also automatically install and configure the spiral/validator package. ```bash composer require spiral/filters-bridge ``` -------------------------------- ### Application Entry Point Source: https://github.com/spiral/docs/blob/3.16/docs/en/framework/dispatcher.md The app.php entry point initializes the application and runs the kernel, which selects the appropriate dispatcher. ```php use App\Application\Kernel; \mb_internal_encoding('UTF-8'); \error_reporting(E_ALL | E_STRICT ^ E_DEPRECATED); \ini_set('display_errors', 'stderr'); require __DIR__ . '/vendor/autoload.php'; $app = Kernel::create( directories: ['root' => __DIR__], )->run(); $code = (int)$app->serve(); // <========== Will run the appropriate dispatcher based on the current environment exit($code); ``` -------------------------------- ### Create and Write Files Source: https://github.com/spiral/docs/blob/3.16/docs/en/advanced/storage.md Demonstrates how to create new files or write content to files using `create()` for empty files and `write()` for files with string or stream content. ```APIDOC ## Create and Write Files ### Description Use `create()` to make an empty file or `write()` to create a file with string or resource stream content. ### Methods - `create(string $destination): FileInterface` - `write(string $destination, string|resource $content): FileInterface` ### Examples ```php // Creating an empty file $file = $bucket->create('file.txt'); // Creating a file with string content $file = $bucket->write('file.txt', 'message'); // Creating a file with resource stream content $file = $bucket->write('file.txt', fopen(__DIR__ . '/local/file.txt', 'rb+')); ``` ``` -------------------------------- ### Sending a GET Request with Parameters Source: https://github.com/spiral/docs/blob/3.16/docs/en/testing/http.md Use the get() method to send a GET request with optional query parameters, headers, and cookies. ```php $http = $this->fakeHttp(); $response = $http->get( uri: '/users', query: ['sort' => 'desc'], headers: ['Content-type' => 'application/json'], cookies: ['token' => 'xxx-xxxx'], ); ``` -------------------------------- ### Spiral Project Setup Commands Source: https://github.com/spiral/docs/blob/3.16/docs/en/cookbook/quick-start.md Terminal commands to download, initialize, migrate, and configure a Spiral demo project. ```terminal ./vendor/bin/rr get php app.php migrate:init php app.php migrate php app.php configure -vv ``` -------------------------------- ### Install spiral/roadrunner-bridge Source: https://github.com/spiral/docs/blob/3.16/docs/en/start/server.md Install the package using Composer. ```bash composer require spiral/roadrunner-bridge ``` -------------------------------- ### Vue.js Main Application Setup Source: https://github.com/spiral/docs/blob/3.16/docs/en/cookbook/simple-chat.md Set up the main Vue.js application instance, including Centrifuge client integration and global property registration. ```js import {createApp} from 'vue' import App from './App.vue' import {Centrifuge} from "centrifuge"; const app = createApp(App) app.use({ install(app, options) { // Get the auth token from x-bearer meta tag const authToken = document.getElementsByName('x-bearer')[0].getAttribute('content') // Register the auth token as a global property app.config.globalProperties.authToken = authToken // Create a new Centrifuge instance const centrifuge = new Centrifuge('ws://127.0.0.1:8081/connection/websocket', { data: {authToken} }); // Store the user data in the global property when the client is connected centrifuge.on('connected', (ctx) => { app.config.globalProperties.user = ctx.data.user }) centrifuge.connect(); // Register the centrifuge instance as a global property app.config.globalProperties.centrifuge = centrifuge } }) app.mount('#app') ``` -------------------------------- ### Registering a booting callback on the application instance Source: https://github.com/spiral/docs/blob/3.16/docs/en/framework/kernel.md Register a callback to be executed before framework bootloaders are booted. This is done after the application instance has been created. ```php $app = MyApp::create( directories: ['root' => __DIR__] ); $app->booting(function () { // ... }); $app->run(); ``` -------------------------------- ### Install Composer Dependencies Source: https://github.com/spiral/docs/blob/3.16/docs/en/start/deployment.md Use 'composer install' with optimization flags to install production dependencies and optimize the autoloader, excluding development packages and scripts. ```terminal composer install --optimize-autoloader --no-dev --no-scripts ``` -------------------------------- ### Initialize Vue.js Project Source: https://github.com/spiral/docs/blob/3.16/docs/en/cookbook/simple-chat.md Use npm to create a new Vue.js project. Follow the prompts to configure project settings. ```terminal npm init vue@latest ``` -------------------------------- ### Install Notifications Package Source: https://github.com/spiral/docs/blob/3.16/docs/en/advanced/notifications.md Use Composer to install the spiral-packages/notifications package. ```terminal composer require spiral-packages/notifications ``` -------------------------------- ### Initialize Migrations Source: https://github.com/spiral/docs/blob/3.16/docs/en/basics/orm.md Run this command to set up the necessary database table for tracking migration statuses before you start using migrations. It's often run automatically. ```bash php app.php migrate:init ``` -------------------------------- ### Install Scheduler Package Source: https://github.com/spiral/docs/blob/3.16/docs/en/advanced/scheduler.md Use Composer to install the spiral-packages/scheduler package. ```bash composer require spiral-packages/scheduler ``` -------------------------------- ### Create and Write Files Source: https://github.com/spiral/docs/blob/3.16/docs/en/advanced/storage.md Use `create()` to make an empty file or `write()` to create a file with string or stream content. ```php $file = $bucket->create('file.txt'); ``` ```php $file = $bucket->write('file.txt', 'message'); ``` ```php $file = $bucket->write('file.txt', fopen(__DIR__ . '/local/file.txt', 'rb+')); ``` -------------------------------- ### Set up RoadRunner Server with Docker Source: https://github.com/spiral/docs/blob/3.16/docs/en/start/server.md Configure a Dockerfile to use a pre-compiled RoadRunner binary from a Docker image. ```dockerfile FROM spiralscout/roadrunner as roadrunner # OR # FROM ghcr.io/roadrunner-server/roadrunner as roadrunner FROM php:8.1-cli # Copy the RoadRunner binary from the roadrunner image to the local bin directory COPY --from=roadrunner /usr/bin/rr /usr/local/bin/rr # Run the RoadRunner server command CMD ["rr", "serve"] ``` -------------------------------- ### Install Data Grid and Cycle Bridge Source: https://github.com/spiral/docs/blob/3.16/docs/en/data-grid/installation.md Use Composer to install the core Data Grid component and the necessary bridge for Cycle ORM. Ensure you have Cycle ORM installed separately. ```bash composer require spiral/data-grid-bridge spiral/cycle-bridge ``` -------------------------------- ### Configure Broadcasting Connections and Drivers Source: https://github.com/spiral/docs/blob/3.16/docs/en/websockets/broadcasting.md Register custom broadcast drivers and connections in the `app/config/broadcasting.php` configuration file. This example shows how to set up 'log', 'pusher', and 'null' connections and alias them. ```php use Spiral\Broadcasting\Driver\LogBroadcast; use Spiral\Broadcasting\Driver\NullBroadcast; use App\Broadcast\PusherBroadcast; return [ 'default' => 'log', 'connections' => [ 'log' => [ 'driver' => 'log', ], 'pusher' => [ 'driver' => 'pusher', ], 'null' => [ 'driver' => NullBroadcast::class, ], ], 'driverAliases' => [ 'log' => LogBroadcast::class, 'pusher' => PusherBroadcast::class, ], ]; ``` -------------------------------- ### Install Stempler Bridge Source: https://github.com/spiral/docs/blob/3.16/docs/en/views/stempler.md Use Composer to install the Stempler bridge extension. ```bash composer require spiral/stempler-bridge ``` -------------------------------- ### Install Spiral Validator Source: https://github.com/spiral/docs/blob/3.16/docs/en/validation/spiral.md Install the Spiral Validator component using Composer. ```terminal composer require spiral/validator ``` -------------------------------- ### Install Twig Bridge Component Source: https://github.com/spiral/docs/blob/3.16/docs/en/views/twig.md Install the Twig bridge component using Composer. ```bash composer require spiral/twig-bridge ``` -------------------------------- ### Dynamic Bootloader Configuration with Closures Source: https://github.com/spiral/docs/blob/3.16/docs/en/framework/bootloaders.md Use a closure to dynamically configure bootloaders, accessing container services like `AppEnvironment` to determine loading conditions or pass arguments. ```php use Spiral\Boot\Environment\AppEnvironment; PrototypeBootloader::class => static fn(AppEnvironment $env) => new BootloadConfig( enabled: $env->isLocal(), args: ['debug' => $env->get('DEBUG')] ), ``` -------------------------------- ### Install Broadcasting Bootloader using Method Source: https://github.com/spiral/docs/blob/3.16/docs/en/websockets/broadcasting.md Add the BroadcastingBootloader class to your application's bootloaders array using the defineBootloaders method. ```php public function defineBootloaders(): array { return [ // ... \Spiral\Broadcasting\Bootloader\BroadcastingBootloader::class, // ... ]; } ``` -------------------------------- ### Install Symfony Validator Component Source: https://github.com/spiral/docs/blob/3.16/docs/en/validation/symfony.md Install the Symfony Validator bridge using Composer. ```bash composer require spiral-packages/symfony-validator ``` -------------------------------- ### Install spiral/views Component Source: https://github.com/spiral/docs/blob/3.16/docs/en/views/configuration.md Install the spiral/views component using composer for alternative builds. ```terminal composer require spiral/views ``` -------------------------------- ### Verify Singleton Behavior Source: https://github.com/spiral/docs/blob/3.16/docs/en/container/configuration.md Demonstrates how to verify that a class is being treated as a singleton by comparing instances retrieved from the container. ```php protected function index(UserService $service): void { dump($this->container->get(UserService::class) === $service); } ``` -------------------------------- ### 创建 Bootloader 的输出 Source: https://github.com/spiral/docs/blob/3.16/docs/zh-CN/framework/bootloaders.md 成功创建 Bootloader 后,将显示确认消息,指示文件已写入。 ```output Declaration of ' [32mGithubClientBootloader [39m' has been successfully written into ' [33mapp/src/Application/Bootloader/GithubClientBootloader.php [39m'. ``` -------------------------------- ### Install Centrifuge Package Source: https://github.com/spiral/docs/blob/3.16/docs/en/cookbook/simple-chat.md Navigate to the project directory and install the Centrifuge npm package. ```terminal cd frontend npm install centrifuge -s ``` -------------------------------- ### Install spiral/nyholm-bridge Source: https://github.com/spiral/docs/blob/3.16/docs/en/http/configuration.md Install the necessary extension using Composer to enable the HTTP component. ```bash composer require spiral/nyholm-bridge ``` -------------------------------- ### Install Spiral Application Bundle Source: https://github.com/spiral/docs/blob/3.16/docs/en/cookbook/simple-chat.md Installs the default spiral/app bundle with necessary components for building the chat application. Follow the prompts to select ORM, validator, and templating engine. ```bash composer create-project spiral/app realtime-chat ``` -------------------------------- ### Install roadrunner-worker Package Source: https://github.com/spiral/docs/blob/3.16/docs/en/cookbook/custom-dispatcher.md Install the necessary package for RoadRunner integration using Composer. ```bash composer require spiral/roadrunner-worker ``` -------------------------------- ### Setup Fake Storage Bucket Source: https://github.com/spiral/docs/blob/3.16/docs/en/testing/storage.md Initialize a fake storage bucket within your test case. This allows for isolated testing of storage interactions without affecting the actual file system or cloud storage. ```php use Tests\TestCase; final class UserServiceTest extends TestCase { private \Spiral\Testing\Storage\FakeBucket $bucket; protected function setUp(): void { parent::setUp(); $this->bucket = $this->fakeStorage()->bucket('avatars'); } public function testUserShouldBeRegistered(): void { // Perform user registration ... $this->bucket->assertCreated('avatars/john_smith.jpg'); } } ``` -------------------------------- ### Install Sentry Bridge Component Source: https://github.com/spiral/docs/blob/3.16/docs/en/basics/errors.md Use Composer to install the Sentry bridge package. ```bash composer require spiral/sentry-bridge ``` -------------------------------- ### Install ScaffolderBootloader using `LOAD` constant Source: https://github.com/spiral/docs/blob/3.16/docs/en/basics/scaffolding.md Alternatively, include the `ScaffolderBootloader` class in the `LOAD` constant within `Kernel.php` to enable the scaffolder component. ```php protected const LOAD = [ // ... \Spiral\Scaffolder\Bootloader\ScaffolderBootloader::class, // ... ]; ``` -------------------------------- ### Install symfony/var-dumper Source: https://github.com/spiral/docs/blob/3.16/docs/en/basics/debug.md Install the symfony/var-dumper package for a more traditional debugging approach with a standalone server. ```bash composer require --dev symfony/var-dumper ``` -------------------------------- ### Format Command Output Source: https://github.com/spiral/docs/blob/3.16/resources/guidelines/how-to-write-documentation.md Use `output` syntax highlighting for command output. Show realistic output examples. ```output Controller "App\Controller\HomeController" created successfully. ``` -------------------------------- ### Install Laravel Validator Bridge Source: https://github.com/spiral/docs/blob/3.16/docs/en/validation/laravel.md Install the Laravel Validator bridge package using Composer. ```bash composer require spiral-packages/laravel-validator ``` -------------------------------- ### Implement Database View Loader Source: https://github.com/spiral/docs/blob/3.16/docs/en/views/basics.md This example demonstrates how to implement a custom view loader that fetches view templates from a database. It requires a DatabaseInterface and defines methods for checking view existence, loading view content, and listing available views. ```php namespace App\Integration\Database; use Spiral\Views\LoaderInterface; use Spiral\Views\Loader\PathParser; use Spiral\Views\ViewSource; final class DatabaseLoader implements LoaderInterface { private ?PathParser $parser = null; public function __construct( private readonly DatabaseInterface $database, private readonly string $defaultNamespace = self::DEFAULT_NAMESPACE, ) {} public function withExtension(string $extension): LoaderInterface { $loader = clone $this; $loader->parser = new PathParser($this->defaultNamespace, $extension); return $loader; } public function getExtension(): ?string { return $this->parser?->getExtension(); } public function exists(string $path, string & $filename = null, ViewPath & $parsed = null): bool { if ($this->parser === null) { throw new LoaderException( 'Unable to locate view source, no extension has been associated.' ); } $parsed = $this->parser->parse($path); if ($parsed === null) { return false; } if (!isset($this->namespaces[$parsed->getNamespace()])) { return false; } // Iterate over all registered namespaces and check if the view exists in // any of them. foreach ((array)$this->namespaces[$parsed->getNamespace()] as $namespace) { $isExists = $this->getTemplate($namespace, $parsed->getBasename()) !== null; if ($isExists) { $filename = $parsed->getBasename(); return true; } } return false; } public function load(string $path): ViewSource { if (!$this->exists($path, $filename, $parsed)) { throw new LoaderException( \sprintf('Unable to load view `%s`, file does not exist.', $path) ); } // View variable contains an array of record from the database with the // following structure: // ['html' => '
...
', 'path' => '...', 'namespace' => '...'] $view = $this->getTemplate($parsed->getNamespace(), $parsed->getBasename()); return (new ViewSource( $filename, $parsed->getNamespace(), $parsed->getName() ))->withCode($view['html']); } public function list(string $namespace = null): array { $views = []; foreach ($this->namespaces as $namespace) { $templates = $this->database->select () ->from('views') ->where('namespace', $namespace) ->fetchAll(); foreach ($templates as $template) { $views[] = $namespace . ':' . $template['path']; } } return $views; } private function getTemplate(string $namespace, string $path): ?array { return $this->database->select () ->from('views') ->where('namespace', $namespace) ->where('path', $path) ->fetchOne(); } } ``` -------------------------------- ### Define Route for Sample Action Source: https://github.com/spiral/docs/blob/3.16/docs/en/filters/filter.md Sets up a route named 'sample' with a dynamic ID parameter. ```php $router->setRoute( 'sample', new Route('/action/.html', new Controller(HomeController::class)) ); ``` -------------------------------- ### Install Temporal Bridge Package Source: https://github.com/spiral/docs/blob/3.16/docs/en/temporal/configuration.md Install the necessary package for Temporal integration using Composer. ```bash composer require spiral/temporal-bridge ``` -------------------------------- ### Install RoadRunner on Debian-based Linux Source: https://github.com/spiral/docs/blob/3.16/docs/en/start/server.md Install RoadRunner on Debian-derivative systems using a .deb package. ```bash wget https://github.com/roadrunner-server/roadrunner/releases/download/v2.X.X/roadrunner-2.X.X-linux-amd64.deb sudo dpkg -i roadrunner-2.X.X-linux-amd64.deb ``` -------------------------------- ### Install Mailer Bootloader using Method Source: https://github.com/spiral/docs/blob/3.16/docs/en/advanced/sendit.md Add the MailerBootloader class to your application's bootloaders array to enable the email component. ```php public function defineBootloaders(): array { return [ // ... \Spiral\SendIt\Bootloader\MailerBootloader::class, // ... ]; } ``` -------------------------------- ### Install Database Seeder Package Source: https://github.com/spiral/docs/blob/3.16/docs/en/cookbook/quick-start.md Install the database seeder package using Composer for development. ```bash composer require spiral-packages/database-seeder --dev ```