Reputation: 155
Ok, I've watched the Laracast videos on the topic and also have read the documentation, still I miss the core point here. Let's say we have the following structure:
So I understood how to create a service provider, bind a class to the service container and resolve it later. But what if MyCustomClass
binding has to be replaced let's say by \App\SomeOtherClass
. That would lead to an exception of missing SomeOtherClass
if I don't reference it. This leads me to the question: "What's the point of using service container, since I still have to reference the bound class again? What am I doing wrong here?
Upvotes: 0
Views: 762
Reputation: 3205
Bind to an interface/contract which both of the swappable classes conform to.
interface CustomInterface
{
public function greeting();
}
class FirstCustomClass implements CustomInterface
{
public function greeting()
{
return 'hello world';
}
}
class SecondCustomClass implements CustomInterface
{
public function greeting()
{
return 'hello world two';
}
}
Then in your service provider bind to Namespace\Of\My\Interface\CustomInterface:class
and then return which ever implementation you want.
Inside of your controller you should dependency inject your Interface, which will then end up giving you the default class.
This then means that you can quickly swap a class for another that has the same interface, or mock it easily when testing.
Upvotes: 2