Метод get класса InputBag
Метод get класса InputBag возвращает значение параметра из входных данных запроса (GET или POST). Первым параметром передаётся имя ключа, вторым - значение по умолчанию, которое возвращается, если ключ не найден. Метод удобен для безопасного извлечения данных, так как исключает ошибку при отсутствии параметра.
Синтаксис
$inputBag->get(string $key, mixed $default = null): mixed
Пример
Давайте извлечём параметр 'name' из GET-запроса в контроллере:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class ArticleController extends AbstractController
{
#[Route('/article', name: 'article_index')]
public function index(Request $request): Response
{
$bag = $request->query;
$res = $bag->get('name', 'guest');
return new Response($res);
}
}
?>
Результат выполнения кода для адреса /article?name=hello:
"hello"
Пример
Давайте получим значение по умолчанию, если параметр отсутствует:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class ArticleController extends AbstractController
{
#[Route('/article', name: 'article_index')]
public function index(Request $request): Response
{
$bag = $request->query;
$res = $bag->get('name', 'guest');
return new Response($res);
}
}
?>
Результат выполнения кода для адреса /article:
"guest"
Пример
Давайте извлечём параметр из POST-запроса через свойство request:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class ArticleController extends AbstractController
{
#[Route('/article', name: 'article_index', methods: ['POST'])]
public function index(Request $request): Response
{
$bag = $request->request;
$res = $bag->get('title', 'empty');
return new Response($res);
}
}
?>
Результат выполнения кода при передаче поля title=abcde:
"abcde"