jenssegers / agent

👮 A PHP desktop/mobile user agent parser with support for Laravel, based on Mobiledetect
https://jenssegers.com
MIT License
4.55k stars 476 forks source link

It would be really cool if you could add Laravel Octane support for this #193

Open KieronWiltshire opened 3 years ago

KieronWiltshire commented 3 years ago

I believe that the only reason Octane doesn't work with this is due to the way how request injection works through the service provider. See https://laravel.com/docs/8.x/octane#request-injection

Basically... the current code always leaves the user agent null.

vodnicearv commented 2 years ago

you can create middleware, and add it Kernel

app()->bind(Agent::class, function ($app) {
      return new Agent($app['request']->server->all(), $app['request']->userAgent());
});
View::share('agent', app(Agent::class));
jangaraev commented 2 years ago

here is how I solved this:

<?php

namespace App\Providers;

use Illuminate\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Jenssegers\Agent\Agent;

class OctaneServiceProvider extends ServiceProvider
{
    private $isRunningInOctane;

    public function register()
    {
        parent::register();

        $this->registerBinding('agent', fn (Application $app) => new Agent($app['request']->server()), Agent::class);
    }

    private function registerBinding(string $name, callable $fn, string $alias): void
    {
        if ($this->runningInOctane()) {
            $this->app->bind($name, $fn, true);
        } else {
            $this->app->singleton($name, $fn);
        }

        $this->app->alias($name, $alias);
    }

    private function runningInOctane(): bool
    {
        if (is_null($this->isRunningInOctane)) {
            $this->isRunningInOctane = !$this->app->runningInConsole() && env('LARAVEL_OCTANE');
        }

        return $this->isRunningInOctane;
    }
}

I created my own service provider to handle those Octane incompatibilities of 3rd party packages in one place. In my real code I use multiple registerBinding() calls as there are several incompatible components.

Don't forget to register it in config/app.php.

Hope it helps.

adityapryg commented 1 year ago

Hi @jangaraev I've tried your suggestion but it doesn't work on me. The user agent still leaves the user agent null.🥲 Is there any things that should I write or config?