I think this is a totally valid curiosity, as it greatly facilitates and speeds development.
I often analyze the framework code I usually use, such as Cakephp 2
, Laravel 4
and Symfony 2
.
I started working shortly with Laravel 5
and realized that there is a functionality in it that I have never seen in any of the frameworks. It is the automatic passing of an instance to the argument of a method of a controller or route, or any other class of the framework, simply by setting the Type Hiting
of the function.
Example:
class AuthController extends Controller
{
public function getIndex(Request $request, UrlGenerator $url)
{
$request->get('nome');
}
}
When you do this in the parameters of getIndex
, you automatically pass this to the method instances of the classes. So, if I do not want to use UrlGenerator
, I can simply remove the parameter declaration from this method, it will not be passed by argument.
That is, no matter the position of the parameters, it always gives me the instance of the typed argument simply because I passed it there.
Another example:
public function getIndex($id, Request $request){}
Or
public function getIndex(Request $request, $id) {}
How can I do this in php? How does Laravel
do this?