W
W
WebDev2017-04-16 11:06:56
Laravel
WebDev, 2017-04-16 11:06:56

How is it implemented in Laravel?

If you create a route like this:

Route::get('product/{id}', '[email protected]');

Then in the controller the parameter should be exactly $id and nothing else:
...
public function index(Product $id)  {
    //$id - продукт
}

That is, you cannot designate a variable as {id} in the route, and accept $product in the controller.
I'm wondering how it's implemented? How to check the names of incoming parameters in php?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
D3lphi, 2017-04-16
@kirill-93

This is called reflection. Example:

$class = new \ReflectionClass('Название класса');  // Создаем объект для рефлексии класса
$method = $class->getMethod('Имя метода');   // Получаем метод по имени
$params = $method->getParameters();   // Получаем массив с параметрами
$paramName = $params[0]->getName();   // Берем первый элемент массива, он имеет тип ReflectionParameter, и получаем его имя.

You can immediately create an object to reflect the method "directly":
$method = new \ReflectionMethod('Класс', 'Имя метода');
// Далее, аналогично

With the help of reflection, you can not only get the names of parameters, but also their types, default values. You can even get dock blocks for methods/properties and so on. With the help of reflection, for example, doctrine orm works. It uses annotations (as one of the configuration options) to describe entities.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question