0

I have an example here from the framework Laravel.

class UserController extends Controller
{
    public function store(Request $request)
    {
        $name = $request->input("name");
    }
}

What I don't understand is that Request is explicitly defined within the function signature of store().

Couldn't php's type inference figure out what is being passed into the function?

Would this even be considered dependency injection?

1
  • Yes, you are simply stating what data type you accept into the function. The class/function has no knowledge of how to instantiate/create that object. If you want to abstract further then use generic 'interfaces when setting up what is acceptable. Commented Aug 4, 2017 at 20:56

1 Answer 1

2

This is method level dependency injection. The Request is being passed into the store method, instead of the store method knowing how to create the Request object.

The type hint in the method signature does two things.

First, for plain PHP, it enforces the fact that the parameter passed to the store method must be a Request object, or an object that inherits from Request. If you attempt to call the store() method with anything other than a Request object (or descendant), you will get an error.

Because of this strict type enforcement, we know that the $request parameter must be a Request object (or descendant), and we can depend on its public interface being available for use (you know the input() method will exist).

Second, for Laravel, it tells the Laravel container what type of object this method needs, so that the correct object can be resolved out of the container and passed to the method. Laravel's controller methods are called through the container, which allows automatic dependency resolution of method calls.

If you were to remove the type hint, this would cause two issues. At an abstract level, it would allow you to pass any type of object, or even scalar values, to the store() method. If you attempt to call input() on a string, you're going to have problems. At a more concrete level, this will break Laravel's automatic dependency resolution of controller methods. Without the type hint, Laravel can't know what object the method requires, so it won't pass in anything, so in reality you'd get an error saying that you can't call input() on null (or an error saying the store method requires one parameter; not sure, didn't test).

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

Comments

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.