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

Os Laravel Package

php-standard-library/os

Type-safe OS detection for PHP via an OperatingSystemFamily enum. Quickly identify Windows, macOS, Linux, and more without brittle string checks. Part of PHP Standard Library; lightweight and focused on reliable environment detection.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require php-standard-library/os:^6.1
    

    Add to composer.json under require:

    "php-standard-library/os": "^6.1"
    
  2. First Usage Detect the current OS family in a Laravel service or controller:

    use PhpStandardLibrary\Os\OperatingSystemFamily;
    
    $osFamily = OperatingSystemFamily::current();
    $isLinux = $osFamily->is(OperatingSystemFamily::LINUX);
    
  3. Key Entry Points

    • OperatingSystemFamily::current() → Returns the detected OperatingSystemFamily enum.
    • $family->is($target) → Type-safe comparison (e.g., is(OperatingSystemFamily::WINDOWS)).
    • $family->value → Raw string (e.g., "linux", "darwin").
    • New in 6.1.2: $family->isDocker() → Check if running in a Docker container (added as a convenience method).

Implementation Patterns

1. Conditional Logic for OS-Specific Features

Use the enum to gate functionality in Laravel services:

public function handle()
{
    $os = OperatingSystemFamily::current();

    if ($os->is(OperatingSystemFamily::WINDOWS)) {
        $this->configureWindowsSpecificSettings();
    }
    elseif ($os->isDocker()) { // New in 6.1.2
        $this->configureDockerSpecificSettings();
    }
}

2. Dependency Injection

Bind the enum to Laravel’s container for reusable access:

// In a service provider
$this->app->singleton(OperatingSystemFamily::class, function () {
    return OperatingSystemFamily::current();
});

// Inject anywhere
public function __construct(private OperatingSystemFamily $os) {}

3. Configuration Overrides

Use the enum to load OS-specific configs (e.g., config/os.php):

$configPath = match (true) {
    $os->isDocker() => 'config/docker.php', // New in 6.1.2
    $os->is(OperatingSystemFamily::WINDOWS) => 'config/windows.php',
    $os->is(OperatingSystemFamily::LINUX) => 'config/linux.php',
    default => 'config/default.php',
};
config([$configPath => require $configPath]);

4. Artisan Commands

Detect OS in CLI tools:

use PhpStandardLibrary\Os\OperatingSystemFamily;

protected function handle()
{
    if (OperatingSystemFamily::current()->isDocker()) { // New in 6.1.2
        $this->warn('Running in Docker. Some features may be limited.');
    }
}

5. Testing

Mock OS detection in tests:

use PhpStandardLibrary\Os\OperatingSystemFamily;

public function testDockerBehavior()
{
    $this->app->instance(OperatingSystemFamily::class, OperatingSystemFamily::DOCKER); // New in 6.1.2
    $this->assertTrue(app(OperatingSystemFamily::class)->isDocker());
}

6. Docker-Specific Logic (New in 6.1.2)

Leverage the new isDocker() method to handle container-specific workflows:

public function runMigrations()
{
    if (OperatingSystemFamily::current()->isDocker()) {
        $this->call('migrate:fresh', ['--env' => 'docker']);
    } else {
        $this->call('migrate');
    }
}

Gotchas and Tips

Pitfalls

  1. Case Sensitivity The enum uses lowercase values ("linux", "windows"), but some systems (e.g., uname on macOS) return "Darwin". The package normalizes this, but verify edge cases like:

    // Avoid hardcoding strings; always use the enum.
    if ($os->value === 'darwin') { ... } // ❌ Fragile
    if ($os->is(OperatingSystemFamily::DARWIN)) { ... } // ✅ Safe
    
  2. Container Binding Conflicts If you bind OperatingSystemFamily::class to the container, ensure it’s not overridden by Laravel’s service providers. Use when() or unless() in bindings:

    $this->app->when(OperatingSystemFamily::class)
              ->needs('$os')
              ->give(fn () => OperatingSystemFamily::current());
    
  3. Dynamic Environments The package detects OS at runtime. For Docker/Kubernetes, test in isolated environments:

    # Test Docker detection
    docker run --rm -it ubuntu bash -c "composer require php-standard-library/os:^6.1 && php -r 'var_dump(\PhpStandardLibrary\Os\OperatingSystemFamily::current()->isDocker());'"
    

Debugging

  • Unexpected Values? Log the raw detection:

    $detector = new \PhpStandardLibrary\Os\OperatingSystemDetector();
    logger()->debug('Raw OS detection:', ['value' => $detector->detect()]);
    

    Common culprits: Docker containers reporting "linux" even on macOS hosts.

  • Docker Detection Issues (New in 6.1.2) If isDocker() returns false unexpectedly, verify Docker’s detection logic:

    // Custom detector for stricter Docker checks
    class StrictDockerDetector extends \PhpStandardLibrary\Os\OperatingSystemDetector
    {
        public function detect(): string
        {
            $os = parent::detect();
            return $os === 'linux' && $this->isDocker() ? 'docker' : $os;
        }
    
        private function isDocker(): bool
        {
            return file_exists('/.dockerenv') || getenv('DOCKER');
        }
    }
    

Tips

  1. Laravel Facades Create a facade for cleaner syntax:

    // app/Facades/Os.php
    public static function family(): OperatingSystemFamily { return OperatingSystemFamily::current(); }
    public static function isDocker(): bool { return self::family()->isDocker(); } // New in 6.1.2
    

    Usage:

    if (Os::isDocker()) { ... } // New in 6.1.2
    
  2. Performance Cache the detection in a singleton if called frequently:

    $this->app->singleton(OperatingSystemFamily::class, fn () => OperatingSystemFamily::current());
    
  3. CI/CD Integration Use the enum to skip OS-specific tests in GitHub Actions:

    jobs:
      test:
        runs-on: ubuntu-latest
        steps:
          - run: php -r "if (\PhpStandardLibrary\Os\OperatingSystemFamily::current()->isDocker()) exit(0); else exit(1);"
    
  4. Local Development Override OS detection for testing:

    // config/os.php
    'override' => env('APP_OS_OVERRIDE', null), // e.g., "windows" or "docker"
    

    Then extend the detector to respect this env var.

  5. Docker-Specific Configs (New in 6.1.2) Load Docker-specific configs dynamically:

    if (OperatingSystemFamily::current()->isDocker()) {
        config(['services' => [
            'redis' => [
                'host' => env('DOCKER_REDIS_HOST', 'redis'),
            ],
        ]]);
    }
    
  6. Backward Compatibility The isDocker() method is additive and does not affect existing code. Existing checks (e.g., is(OperatingSystemFamily::LINUX)) remain unchanged.

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.
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge