Acorn Documentation

repository·main·Indexed 21 days ago

https://github.com/roots/acorn

Acorn is a framework that brings the Laravel ecosystem to WordPress. It allows developers to use Blade templates, Laravel packages, and core illuminate components—such as routing, caching, events, and validation—within WordPress projects to implement cleaner architectural patterns.

Tokens
16K
Snippets
78
Records
91
Agent score
75%

What's inside Acorn

  1. Overview of Acorn

    main

    Acorn is a bridge that allows you to use the Laravel ecosystem within WordPress projects. It enables developers to leverage Laravel's powerful features and patterns while working inside a WordPress environment.

    Key capabilities include:

    • Using Blade templates for WordPress views, blocks, and other components.
    • Accessing core Laravel features like routing, caching, events, and validation directly in WordPress.
    • Utilizing Laravel packages within your WordPress workflow.
    • Applying Laravel's architectural patterns to write cleaner WordPress code.
  2. Manage cloud queues with the Queue class

    main

    The Illuminate\Foundation\Cloud\Queue class acts as a decorator for an underlying queue implementation, providing enhanced monitoring and event emission capabilities. It implements QueueContract and ClearableQueue, allowing you to push, pop, and manage job sizes while automatically emitting cloud events for job lifecycles (queued, started, processed, failed, released).

    Key capabilities include:

    • Job Dispatching: Push jobs normally, push to specific queues, or schedule jobs for later execution.
    • Queue Monitoring: Retrieve sizes for pending, delayed, and reserved jobs.
    • Lifecycle Events: Automatically emits events when jobs are queued, popped (started), or finished (processed/failed/released).
    use Illuminate\Foundation\Cloud\Queue;
    
    // The Queue class wraps an underlying QueueContract implementation
    $cloudQueue = new Queue($underlyingQueue, $events, $config);
  3. Configure the application via app.php

    main

    The config/app.php file is the primary configuration stub for the Acorn application. It defines core application settings such as the name, environment, debug mode, URL, and localization. Most values are driven by environment variables (via the env() helper) to allow for different configurations across development, staging, and production environments.

    Key configuration areas include:

    • Identity: name and url.
    • Environment: env (defaults to WP_ENV or production) and debug (driven by WordPress WP_DEBUG constants).
    • Localization: locale, fallback_locale, and faker_locale.
    • Security: cipher and key (for encryption services).
    • Maintenance: Driver and storage settings for maintenance mode.
    return [
        'name' => env('APP_NAME', 'Acorn'),
        'env' => defined('WP_ENV') ? WP_ENV : env('WP_ENV', 'production'),
        'debug' => WP_DEBUG && WP_DEBUG_DISPLAY,
        'url' => env('APP_URL', home_url()),
        'timezone' => 'UTC',
        'locale' => env('APP_LOCALE', get_locale()),
        'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
        'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
        'cipher' => 'AES-256-CBC',
        'key' => env('APP_KEY'),
        'previous_keys' => [...],
        'maintenance' => [
            'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
            'store' => env('APP_MAINTENANCE_STORE', 'database'),
        ],
    ];
  4. Configure core application settings in config/app.php

    main

    The config/app.php file defines the fundamental behavior and environment settings for the Acorn application. Many values are pulled from environment variables (via env()) or WordPress globals, allowing for easy configuration via a .env file.

    Key Configuration Options

    • name: The application name used in notifications or UI elements. Defaults to Acorn (via APP_NAME).
    • env: The current environment (e.g., production, local). It checks the WP_ENV constant first, then the WP_ENV environment variable, defaulting to production.
    • debug: Boolean determining if detailed error messages and stack traces are shown. It is driven by the WordPress WP_DEBUG and WP_DEBUG_DISPLAY constants.
    • url: The base URL used by the Artisan CLI to generate URLs. Defaults to the WordPress home_url().
    • frontend_url: The URL for the frontend application (e.g., a decoupled React/Vue app). Defaults to http://localhost:3000 (via FRONTEND_URL).
    • asset_url: The URL used to locate assets.
    • timezone: The default PHP timezone. Defaults to UTC.
    • locale: The default locale for translations. Defaults to the WordPress locale (via get_locale()) or APP_LOCALE.
    • fallback_locale: The locale used when the primary locale is unavailable. Defaults to en (via APP_FALLBACK_LOCALE).
    • faker_locale: The locale used by the Faker library for generating dummy data. Defaults to en_US (via APP_FAKER_LOCALE).
    • key: The encryption key for Laravel's encryption services (via APP_KEY).
    • previous_keys: An array of previous encryption keys, provided as a comma-separated list in the APP_PREVIOUS_KEYS environment variable. This is useful for rotating keys without losing access to previously encrypted data.
    • maintenance: Configuration for maintenance mode.
      • driver: The driver used to manage maintenance mode. Supported: file, cache.
      • store: The storage mechanism for maintenance status (e.g., database).
  5. Register Service Providers and Class Aliases

    main

    Acorn uses the providers and aliases arrays in config/app.php to bootstrap the application's features and facades.

    Service Providers

    The providers array contains all service providers that are automatically loaded on every request. You can extend this list using the merge() method on the default providers provided by Roots\Acorn\ServiceProvider.

    Class Aliases

    The aliases array registers class aliases (Facades) that are available throughout the application. These are lazy-loaded for performance. You can extend the default aliases using Illuminate\Support\Facades\Facade::defaultAliases().

    To add new providers or aliases, use the merge() method within the configuration file to ensure you are building upon the existing defaults.

    'providers' => ServiceProvider::defaultProviders()->merge([
            // Package Service Providers...
        ])->merge([
            // Application Service Providers...
            // App\Providers\AppServiceProvider::class,
        ])->merge([
            // Added Service Providers (Do not remove this line)...
        ])->toArray(),
    
    'aliases' => Facade::defaultAliases()->merge([
            // 'Example' => App\Facades\Example::class,
        ])->toArray(),
  6. Customize the documentation opening strategy via environment variables

    main

    You can control how the docs command opens URLs using the following environment variables:

    • ARTISAN_DOCS_OPEN_STRATEGY: If set, the command will attempt to require the file path provided in this variable. The required file must return a callable that accepts a $url string. This is useful for complex environments where a simple command execution isn't enough.

    Alternatively, you can use ARTISAN_DOCS_ASK_STRATEGY to provide a custom callable that determines which documentation page should be opened when the command is run interactively.

  7. Supported Laravel components in Acorn

    main

    Acorn provides access to a wide range of illuminate components out of the box.

    Supported components:

    • illuminate/auth
    • illuminate/bus
    • illuminate/cache
    • illuminate/collections
    • illuminate/conditionable
    • illuminate/config
    • illuminate/console
    • illuminate/container
    • illuminate/contracts
    • illuminate/cookie
    • illuminate/database
    • illuminate/encryption
    • illuminate/events
    • illuminate/filesystem
    • illuminate/hashing
    • illuminate/http
    • illuminate/log
    • illuminate/macroable
    • illuminate/pagination
    • illuminate/pipeline
    • illuminate/queue
    • illuminate/routing
    • illuminate/session
    • illuminate/support
    • illuminate/validation
    • illuminate/view

    Unsupported components:

    • illuminate/broadcasting
    • illuminate/mail
    • illuminate/notifications
    • illuminate/redis
    • illuminate/translation
  8. Configure middleware groups

    main

    Middleware groups allow you to bundle middleware for specific route types (like web or api).

    • group(string $group, array $middleware): Defines a new custom middleware group.
    • prependToGroup(string $group, array|string $middleware): Adds middleware to the start of an existing group.
    • appendToGroup(string $group, array|string $middleware): Adds middleware to the end of an existing group.
    • removeFromGroup(string $group, array|string $middleware): Removes middleware from a specific group.
    • replaceInGroup(string $group, string $search, string $replace): Replaces a specific middleware within a group.

    Specialized helpers for common groups:

    • web(array|string $append = [], array|string $prepend = [], array|string $remove = [], array $replace = []): Modifies the web group.
    • api(array|string $append = [], array|string $prepend = [], array|string $remove = [], array $replace = []): Modifies the api group.
    // Define a custom group
    $middleware->group('admin', [\App\Http\Middleware\AdminMiddleware::class]);
    
    // Modify the existing 'web' group
    $middleware->web(append: [\App\Http\Middleware\CustomWebMiddleware::class]);
    
    // Modify the existing 'api' group
    $middleware->api(prepend: 'auth.basic');
  9. Register a Closure-based command with `command()`

    main

    You can register a quick, one-off command using a Closure. This is useful for simple tasks that don't require a full class definition. The command is registered with the Artisan application instance.

    $kernel->command('say:hello {name}', function ($name) {
        $this->info("Hello, {$name}!");
    });
  10. Configure middleware priority

    main

    Define the order in which middleware should be executed to resolve dependency issues.

    • priority(array $priority): Sets the entire middleware priority list.
    • prependToPriorityList($before, $prepend): Inserts a middleware before a specific existing middleware in the priority list.
    • appendToPriorityList($after, $append): Inserts a middleware after a specific existing middleware in the priority list.
    $middleware->priority([
        \Illuminate\Cookie\Middleware\EncryptCookies::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // ...
    ]);
    
    $middleware->prependToPriorityList(\Illuminate\Session\Middleware\StartSession::class, \App\Http\Middleware\MyMiddleware::class);