Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Hosting Laravel Package

21torr/hosting

21torr/hosting is a small Symfony bundle providing essential tools for hosting Symfony-based applications, helping streamline deployment and operations with basic hosting utilities and sensible defaults.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle:

    composer require 21torr/hosting-bundle
    

    Ensure your config/bundles.php includes:

    return [
        // ...
        HostingBundle\HostingBundle::class => ['all' => true],
    ];
    
  2. Configure Basic Hosting Tier: Update config/packages/21torr_hosting.yaml:

    21torr_hosting:
        tier: production  # or 'staging', 'development'
        build_info:
            app_version: '1.0.0'
            # Custom metadata (e.g., git_commit, build_timestamp)
    
  3. First Use Case: Environment Awareness Access the hosting environment in controllers/services:

    use HostingBundle\Environment\HostingEnvironment;
    
    public function someAction(HostingEnvironment $env)
    {
        if ($env->isDebug()) {
            // Enable debug-specific logic
        }
        return $this->json($env->getTier());
    }
    
  4. Trigger Hooks Manually: Run post-build/deploy hooks during CI/CD:

    php bin/console hosting:hook:build
    php bin/console hosting:hook:deploy
    

Implementation Patterns

Core Workflows

1. Environment-Driven Logic

  • Pattern: Use HostingEnvironment to gate features by tier/debug mode.
    if ($env->getTier() === 'production') {
        $this->mailer->sendTransactional(...);
    }
    
  • Tip: Combine with Symfony’s %kernel.environment% for fallback logic:
    $isProduction = $env->getTier() === 'production' || $env->isDebug() === false;
    

2. Build/Deploy Hooks

  • Pattern: Register custom hooks for post-build/deploy tasks.
    # config/packages/21torr_hosting.yaml
    21torr_hosting:
        hooks:
            build:
                - App\Hook\OptimizeAssetsHook
            deploy:
                - App\Hook\CacheWarmupHook
                - App\Hook\SendDeploymentNotificationHook
    
  • Hook Interface:
    use HostingBundle\Hook\BuildHookInterface;
    
    class OptimizeAssetsHook implements BuildHookInterface {
        public function run(): void {
            // Run asset optimization (e.g., Symfony Encore)
        }
    }
    

3. Health Checks

  • Pattern: Extend default Doctrine health checks or add custom checks.
    use HostingBundle\HealthCheck\HealthCheckInterface;
    
    class DatabaseConnectionCheck implements HealthCheckInterface {
        public function check(): bool {
            return $this->connection->isConnected();
        }
    }
    
  • Register in config/packages/21torr_hosting.yaml:
    21torr_hosting:
        health_checks:
            - App\HealthCheck\DatabaseConnectionCheck
    

4. Build Info Integration

  • Pattern: Use BuildInfo to track deployments (e.g., in logs or metrics).
    use HostingBundle\BuildInfo\BuildInfo;
    
    public function logDeployment(BuildInfo $buildInfo)
    {
        $this->logger->info('Deployed version', [
            'version' => $buildInfo->get('app_version'),
            'built_at' => $buildInfo->get('built'),
        ]);
    }
    
  • CI/CD Tip: Automate build info updates via Git hooks or CI scripts:
    php bin/console hosting:build-info:set --key=git_commit --value=$(git rev-parse HEAD)
    

5. Configuration Overrides

  • Pattern: Override tier-specific configs using Symfony’s environment variables.
    # config/packages/21torr_hosting.yaml
    21torr_hosting:
        tier: '%env(HOSTING_TIER)%'  # Defaults to 'production'
    
  • Example: Use in services.yaml:
    App\Service\FeatureFlag:
        arguments:
            $isEnabled: '%env(bool:FEATURE_FLAG_ENABLED)%'
    

Integration Tips

Symfony Ecosystem

  • Monolog: Use HostingEnvironment to set log levels:
    $logger->setLevel($env->isDebug() ? Logger::DEBUG : Logger::INFO);
    
  • Cache: Tier-aware cache prefixes:
    $cache->get('key', $env->getTier() . ':prefix');
    
  • Messenger: Route messages by environment:
    $message->setTransport($env->isDebug() ? 'sync' : 'async');
    

CI/CD Pipelines

  • GitHub Actions: Trigger hosting:validate-app in CI:
    - name: Validate App
      run: php bin/console hosting:validate-app
    
  • Deploy Scripts: Chain hooks with deployment steps:
    #!/bin/bash
    php bin/console doctrine:migrations:migrate --no-interaction
    php bin/console hosting:hook:deploy
    

Multi-Tenant Extensions

  • Pattern: Use HostingEnvironment to isolate tenant-specific configs:
    $tenantConfig = $this->configLoader->load(
        sprintf('tenants/%s/config.yaml', $env->getTier())
    );
    

Gotchas and Tips

Pitfalls

  1. Configuration Key Changes (v4+)

    • Issue: The config key changed from hosting to 21torr_hosting in v4.0.0.
    • Fix: Update config/packages/21torr_hosting.yaml and clear cache:
      php bin/console cache:clear
      
  2. Debug Mode Confusion

    • Issue: HostingEnvironment::isDebug() reflects %kernel.debug%, not the hosting tier.
    • Fix: Use $env->getTier() === 'development' for tier-specific logic.
  3. Build Info Caching

    • Issue: Build info is no longer cached by default (v4.1.1+), which may slow down CI.
    • Fix: Pre-generate build info in CI:
      php bin/console hosting:build-info:generate
      
  4. Doctrine Health Check Quirks

    • Issue: The DoctrineHealthCheckListener ignores doctrine_migration_versions tables by default.
    • Fix: Exclude additional tables in config:
      21torr_hosting:
          doctrine_health_check:
              ignored_tables: ['migration_versions', 'custom_table']
      
  5. Hook Execution Order

    • Issue: Hooks run in the order they’re defined in config/packages/21torr_hosting.yaml.
    • Fix: Use explicit ordering with tags:
      services:
          App\Hook\FirstHook:
              tags: [hosting.hook.build]
          App\Hook\SecondHook:
              tags: [hosting.hook.build]
              priority: 10  # Runs after FirstHook
      

Debugging Tips

  1. Validate Config Use the hosting:validate-app command to catch misconfigurations early:

    php bin/console hosting:validate-app --env=prod
    
  2. Inspect Build Info Dump build info to debug deployments:

    php bin/console hosting:build-info:show
    
  3. Health Check Debugging Enable verbose health check output:

    php bin/console debug:health-check --verbose
    
  4. Hook Debugging Add logging to hooks to trace execution:

    use Psr\Log\LoggerInterface;
    
    class MyHook implements BuildHookInterface {
        public function __construct(private LoggerInterface $logger) {}
    
        public function run(): void {
            $this->logger->debug('Hook executed');
            // ...
        }
    }
    

Extension Points

  1. Custom Health Checks Extend the HealthCheckInterface to add application-specific checks (e.g., external API availability):

    class ExternalApiCheck implements HealthCheckInterface {
        public function check(): bool {
            return $this->httpClient->get('https://api.example.com/health')->getStatusCode() === 200;
        }
    }
    
  2. Dynamic Tier Resolution Override HostingEnvironment to resolve tiers dynamically (e.g., from a database):

    use HostingBundle\Environment\HostingEnvironment;
    
    class CustomHostingEnvironment extends HostingEnvironment {
        public function getTier(): string {
            return $this->tenantService->getCurrentTenantTier();
        }
    }
    

    Register as a service:

    services:
        HostingBundle\Environment\HostingEnvironment: '@App\Environment\Custom
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
datacore/hub-sdk
alengo/sulu-http-cache-bundle
croct/coding-standard
croct/plug-php
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php
trappistes/laravel-custom-fields