Метод has класса Session
Метод has класса Session проверяет,
существует ли указанный ключ в хранилище сессии.
Первым параметром передаётся имя ключа в виде строки.
Метод возвращает true, если ключ присутствует,
и false в противном случае.
Синтаксис
public function has(string $name): bool
Пример
Давайте проверим наличие ключа user в сессии:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpFoundationSessionSessionInterface;
use SymfonyComponentRoutingAttributeRoute;
class ArticleController extends AbstractController
{
#[Route('/article', name: 'article_index')]
public function index(SessionInterface $session): Response
{
$session->set('user', 'abcde');
return new Response($session->has('user') ? 'true' : 'false');
}
}
?>
Результат выполнения кода:
"true"
Пример
Давайте проверим наличие ключа, которого нет в сессии:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpFoundationSessionSessionInterface;
use SymfonyComponentRoutingAttributeRoute;
class ArticleController extends AbstractController
{
#[Route('/article', name: 'article_index')]
public function index(SessionInterface $session): Response
{
return new Response($session->has('user') ? 'true' : 'false');
}
}
?>
Результат выполнения кода:
"false"
Пример
Давайте сохраним массив данных в сессии и проверим наличие одного из ключей:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpFoundationSessionSessionInterface;
use SymfonyComponentRoutingAttributeRoute;
class ArticleController extends AbstractController
{
#[Route('/article', name: 'article_index')]
public function index(SessionInterface $session): Response
{
$session->set('items', [1, 2, 3, 4, 5]);
if ($session->has('items')) {
return new Response('items found');
}
return new Response('items not found');
}
}
?>
Результат выполнения кода:
"items found"