user2115377
user2115377

Reputation:

ServiceProvider not loaded

Im trying to setup a facade for my Gravatar library.

Problem

The problem I have is the following,the ServiceProvider does not get registert. So 'gravatar' is not in the IoC.

I added \Log::info('initialized'); to my ServiceProvider but nothing is logged.

Error

Call to undefined method Facade\Gravatar::getUrl()

Code

http://paste.laravel.com/AgO

Upvotes: 0

Views: 165

Answers (1)

fideloper
fideloper

Reputation: 12293

So, a Facade takes (potential) three classes:

  1. The class which has the methods you'll use, in this case Gravatar::getUrl()
  2. The Facade class which tells Laravel where to find the class in point 1
  3. The ServiceProvider, which creates the class with the methods, via the $app container.

See here on creating facades in Laravel for some more info.

In your case, I don't see the code from point 1.

The class

Libraries/Gravatar/Avatar.php

<?php namespace Gravatar;

class Avatar {

    public function getUrl() { ...  }

}

The Facade

Libraries/Gravatar/Facade.php

<?php namespace Gravatar;

use Illuminate\Support\Facades\Facade as BaseFacade;

class Facade extends BaseFacade {

    protected static function getFacadeAccessor() {
    return 'gravatar';
}

}

The Service Provider

Libraries/Gravatar/GravatarServiceProvider.php

<?php namespace Gravatar;

use Illuminate\Support\ServiceProvider

class GravatarServiceProvider extends ServiceProvider {

    public function register() {
    Log::info('initialized');
    $this->app['gravatar'] = $this->app->share(function () {
        return new Avatar();
    });
}

}

Tie together in app/config/app.php

<?php
'providers' => array(
...
'Gravatar\GravatarServiceProvider'
),
'aliases' => array(
...
'Gravatar'        => 'Gravatar\Facade'
),

Note

Note that I the namespace I used assumes this directory structure:

Libraries
    Gravatar
        Avatar.php
        GravatarServiceProvider.php
        Facade.php

With autoloading like this in composer.json:

"autoload": {
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/database/migrations",
        "app/tests/TestCase.php"
    ],
    "psr-0": {
        "Gravatar": "app/Library" // Or wherever your Library directory is
    }
},

If you're confused on Namespacing and how that works with autoloading, read up on PSR-0.

Hope that helps!

Upvotes: 2

Related Questions