laravel-Meta icon indicating copy to clipboard operation
laravel-Meta copied to clipboard

Dependency injection mixed with Facade usage

Open alexjoffroy opened this issue 7 years ago • 3 comments

I'm facing a problem when I inject the \Eusonlito\LaravelMeta\Meta instance in my controller and then trying to get the tags in my view (with the Facade).

Here's a basic example:

Route::get('/', function (\Eusonlito\LaravelMeta\Meta $meta) {
    $meta->set('title', 'Hello world');

    dd(Meta::get('title'));
});

As I expect this bit of code to dump 'Hello world', it actually dumps 'null'. It seems that the instance returned by the Meta Facade is not the same as the one retrieved by the injection mecanism.

When looking at the MetaServiceProvider, I first thought it requires to define an alias like this:

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(Meta::class, function () {
            return new Meta(config('meta'));
        });

        $this->app->alias(Meta::class, 'meta');
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [Meta::class, 'meta'];
    }

But still not working.

Anyone else facing this issue ?

alexjoffroy avatar Jan 31 '18 15:01 alexjoffroy

Please load the package as is explained in README:

// config/app.php

'providers' => [
    '...',
    Eusonlito\LaravelMeta\MetaServiceProvider::class
];

'aliases' => [
    '...',
    'Meta'    => Eusonlito\LaravelMeta\Facade::class,
];
php artisan vendor:publish --provider="Eusonlito\LaravelMeta\MetaServiceProvider"
// Are you in a namespace?
use Meta;

Route::get('/', function () {
    Meta::set('title', 'Hello world');

    dd(Meta::get('title'));
});

eusonlito avatar Jan 31 '18 18:01 eusonlito

Yes, when using the Facade to set the meta, it works: no problem with that.

My issue is when I try to resolve the Meta object from the container, as explained here: https://laravel.com/docs/5.5/container#automatic-injection

alexjoffroy avatar Feb 01 '18 08:02 alexjoffroy

Ok, I finally managed to make it work. I missed a composer dump-autoload after manually editing MetaServiceProdvider in my vendors.

Will soon submit a PR to fix this :)

alexjoffroy avatar Feb 01 '18 10:02 alexjoffroy