5

I am new to all this stuff. I mean I understand how OOP works but not really. I guess every novice developer was at my place at some point. So I have been going through Jeffrey's awesome Laracasts to understand how this stuff really works.

So I just completed a lesson on Interfaces where he explained "Always work with interfaces and never with implementations" and makes sense to me but I have a doubt with the last example which goes like:

Interface example

He explains how CanBeFiltered Interface is useful and I get it that if I pass this interface into a constructor of a controller, Laravel will, behind the scenes, resolve a particular filter of my choice and inject it and then I will be able to use it. Or I can do it manually like so:

<?php

class UserController{

    protected $canBeFiltered;

    public function __construct(CanBeFiltered $canBeFiltered)
    {
        $this->canBeFiltered = $canBeFiltered;
    }

    public function show()
    {
        return $this->canBeFiltered->filter();
    }
}

$controller = new UserController(new Favorited);

And this will basically apply the favorited filter but what if I want to apply multiple filters like if I want to apply favorited and unwatched? What do I do then?

And moreover, Laravel's IoC container will automatically resolve dependencies for me so how will pass different filters to different controllers?

1
  • 1
    Use when()->needs()->give(). See here. Commented Aug 13, 2015 at 21:16

1 Answer 1

4

Each interface can have different implementations so when you are type hinting dependencies in a constructor, laravel will ask the service container to find out if there is any binded implementation for that interface or not.
its the developer who must specify which of the implementations must be used for resolving of interface dependencies and laravel also supports Contextual Binding which means that you may have two classes that utilize the same interface, but you wish to inject different implementations into each class. for more info check out the documentation.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes but how do I still use two filters in the same class?
I don't understand it, why you want to use 2 filters but if you need two filters then define them in your Interface and other classes that are going to implement that Interface can easily implement those two filters. you can also use PHP traits to have as much filters as you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.