Symfony Scoped HttpClient
# .env file
SLACK_WEBHOOK_BASE_URL='https://hooks.slack.com'
APP_SLACK_WEBHOOK_YOUR_CHANNEL_ADDRESS='your channel address'
We define the required settings in the env file.
// config/packages/framework.yaml
framework:
...
http_client:
scoped_clients:
slack_webhook_client:
base_uri: '%env(resolve:SLACK_WEBHOOK_BASE_URL)%'
timeout: 2.0*/
We define scoped HTTP clients in our framework configuration file. I couldn’t find any Attribute usage for this in the documentation.
<?php
namespace App\Service;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Throwable;
readonly class SlackService
{
public function __construct(
#[Autowire(service: 'slack_webhook_client')]
private HttpClientInterface $slackClient,
#[Autowire(env: 'APP_SLACK_WEBHOOK_YOUR_CHANNEL_ADDRESS')]
private string $yourChannelAddress,
private LoggerInterface $logger
)
{
}
public function sendText(string $text): void
{
try {
$this->slackClient->request(
Request::METHOD_POST,
$this->yourChannelAddress,
[
'json' => ['text' => $text],
]
);
} catch (Throwable $exception) {
$this->logger->warning($exception->getMessage());
}
}
}
5 месяцев назад