Метод has
Метод has класса Container проверяет,
зарегистрирован ли сервис с указанным идентификатором
в контейнере зависимостей. Первым параметром
передаётся строковый идентификатор сервиса.
Метод возвращает true, если сервис существует,
и false в противном случае.
Синтаксис
public function has(string $id): bool
Пример
Давайте проверим наличие стандартного сервиса
request_stack в контейнере:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
use PsrContainerContainerInterface;
class ArticleController extends AbstractController
{
#[Route('/check', name: 'article_check')]
public function check(ContainerInterface $container): Response
{
$res = $container->has('request_stack');
return new Response(var_export($res, true));
}
}
?>
Результат выполнения кода:
true
Пример
Давайте проверим наличие несуществующего сервиса
non_existent_service:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
use PsrContainerContainerInterface;
class ArticleController extends AbstractController
{
#[Route('/missing', name: 'article_missing')]
public function missing(ContainerInterface $container): Response
{
$res = $container->has('non_existent_service');
return new Response(var_export($res, true));
}
}
?>
Результат выполнения кода:
false
Пример
Давайте используем метод has для условного
получения сервиса. Если сервис существует,
вернём его класс, иначе выведем сообщение:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
use PsrContainerContainerInterface;
class ArticleController extends AbstractController
{
#[Route('/service', name: 'article_service')]
public function service(ContainerInterface $container): Response
{
if ($container->has('request_stack')) {
$service = $container->get('request_stack');
$res = get_class($service);
} else {
$res = 'Service not found';
}
return new Response($res);
}
}
?>
Результат выполнения кода:
"SymfonyComponentHttpFoundationRequestStack"
Смотрите также
-
класс
Container,
который управляет сервисами приложения -
метод
get,
который возвращает сервис из контейнера -
метод
initialized,
который проверяет, был ли сервис инициализирован -
интерфейс
ContainerBag,
который предоставляет доступ к параметрам контейнера