This is driving me bonkers because it seems I'm the only person with this problem.
I have a UserMessage Contract
namespace App\Contracts;
interface UserMessageContract
{
public function send($user, $message);
}
Then I have the concrete class:
namespace App\Support\UserMessage;
class UserMessage implements UserMessageContract
{
//some code here
}
Then the service provider:
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Support\UserMessage\UserMessage;
use App\Contracts\UserMessageContract;
class UserMessageProvider extends ServiceProvider
{
protected $defer = true;
public function register()
{
$this->app->singleton('usermessage', function ($app)
{
return new UserMessage();
});
$this->app->alias('usermessage', UserMessageContract::class);
}
public function provides()
{
return ['usermessage'];
}
}
When I try to inject this into a controller, it gives me the "not instantiable" error.
I've tracked down the problem to the fact that the alias is not binding 'usermessage' to 'UserMessageContract::class'. For example, if I add 'usermessage' => UserMessageContract::class to the $alias array in Application.php, it works and the class gets resolved.
But currently it seems the error is thrown before the UserMessageProvider register function is even being called, so the alias is never registered. What am I doing wrong? I've read the documentation and looked at the source code to make sure I do it the way it's currently being done in source.
Is there another place I should register the alias?
Ok, so changing the service provider like so:
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Support\UserMessage\UserMessage;
use App\Contracts\UserMessageContract;
class UserMessageProvider extends ServiceProvider
{
protected $defer = true;
public function register()
{
$this->app->singleton(UserMessageContract::class, function ($app)
{
return new UserMessage();
});
$this->app->alias(UserMessageContract::class, 'usermessage');
}
public function provides()
{
return [UserMessageContract::class, 'usermessage'];
}
}
gives the desired result. The class gets resolved out of the IoC container and I can still use the alias, i.e app('usermessage');
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community