Installation
composer require creatissimo/mattermost-bundle
Ensure your project uses Symfony 3.4 (or adjust compatibility if using a newer version via flex overrides).
Enable the Bundle
Add to config/bundles.php:
Creatissimo\MattermostBundle\CreatissimoMattermostBundle::class => ['all' => true],
Basic Configuration
Add to config/packages/creatissimo_mattermost.yaml:
creatissimo_mattermost:
webhook: "https://your-mattermost-instance/hooks/abc123"
appname: "MyApp"
username: "AppBot"
channel: "#general"
icon_url: "https://example.com/logo.png"
First Use Case: Sending a Message Inject the service in a controller or command:
use Creatissimo\MattermostBundle\Service\MattermostService;
class MyController extends AbstractController
{
public function __construct(private MattermostService $mattermost) {}
public function sendAlert()
{
$this->mattermost->sendMessage("Hello from Symfony!");
}
}
Environment-Specific Configs
Leverage the environments key to override settings per environment (e.g., dev vs. prod):
environments:
dev:
channel: "#dev-alerts"
exception:
trace: false # Disable stack traces in dev
Exception Handling Automatically log exceptions to Mattermost:
// In a service or controller
try {
// Risky operation
} catch (\Exception $e) {
$this->mattermost->sendException($e);
}
Configure exclusions in yaml to filter specific exceptions (e.g., NotFoundHttpException).
Command-Line Integration Use in Symfony console commands for CI/CD or cron jobs:
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class DeployCommand extends Command
{
protected static $defaultName = 'app:deploy';
public function __construct(private MattermostService $mattermost) {}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->mattermost->sendMessage("Deploy started!");
// ... deployment logic ...
$this->mattermost->sendMessage("Deploy completed!");
return Command::SUCCESS;
}
}
Termination Notifications Hook into Symfony’s kernel events to notify on process termination:
terminate:
enable: true
exclude_exitcode: [0, 255] # Ignore success/failure codes
Trigger via event listener:
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class MattermostTerminateSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [TerminateEvent::class => 'onTerminate'];
}
public function __construct(private MattermostService $mattermost) {}
public function onTerminate(TerminateEvent $event): void
{
$this->mattermost->sendTerminationMessage($event->getRequest()->getServerParams());
}
}
MattermostService in controllers/services.webhook).$this->mattermost->sendMessage("Alert!", 3); // Retry 3 times
channel dynamically based on context:
$this->mattermost->setChannel("#" . $user->getTeam()->getSlug());
$this->mattermost->sendMessage("Team update!");
Deprecated Symfony Version The bundle targets Symfony 3.4. For Symfony 5/6:
symfony/flex to override dependencies or fork the bundle.EventDispatcher calls with Symfony 5’s EventDispatcherInterface.Webhook Authentication Mattermost webhooks require incoming webhook URLs (not generic URLs). Ensure:
webhook URL is from Mattermost’s Integrations > Incoming Webhooks.username and icon_url are set correctly (Mattermost validates these).Exception Trace Length
Long stack traces may be truncated. Configure exception.trace carefully:
exception:
trace: true
max_trace_length: 500 # Customize if needed (not natively supported; extend the service)
Async Operations Sending messages synchronously blocks execution. For high-throughput apps:
Messenger component to queue messages:
$this->messenger->dispatch(new MattermostMessage($message));
doctrine/messenger or symfony/messenger.Configuration Overrides Avoid hardcoding values in services. Always use dependency-injected configs:
// ❌ Anti-pattern
$this->mattermost->setWebhook("hardcoded-url");
// ✅ Preferred
$this->mattermost->sendMessage("..."); // Uses injected config
Enable Verbose Logging
Add to config/packages/monolog.yaml:
handlers:
mattermost:
type: stream
path: "%kernel.logs_dir%/mattermost.log"
level: debug
Then enable debug mode in the bundle’s service:
debug: true # Add to root config
HTTP Client Errors If messages fail silently:
webhook URL format (must include /hooks/).GuzzleHttp\Exception\RequestException to catch HTTP errors:
try {
$this->mattermost->sendMessage("Test");
} catch (RequestException $e) {
// Log $e->getResponse()->getBody()
}
Channel Permissions
Ensure the Mattermost user (configured via username) has post permissions in the target channel.
Custom Message Formats
Extend the MattermostService to add fields like attachments or props:
// src/Service/ExtendedMattermostService.php
class ExtendedMattermostService extends MattermostService
{
public function sendFormattedMessage(string $text, array $props = []): void
{
$this->sendMessage($text, [
'props' => $props,
'mrkdwn' => true,
]);
}
}
Register as a service alias:
services:
Creatissimo\MattermostBundle\Service\MattermostService:
alias: App\Service\ExtendedMattermostService
Event Listeners Subscribe to Symfony events to auto-send messages:
// src/EventListener/MattermostListener.php
class MattermostListener implements KernelEvents
{
public function __construct(private MattermostService $mattermost) {}
public function onKernelRequest(GetResponseEvent $event): void
{
if ($event->isMainRequest()) {
$this->mattermost->sendMessage("Request received: " . $event->getRequest()->getPathInfo());
}
}
}
Testing Mock the service in PHPUnit:
$mockMattermost = $this->createMock(MattermostService::class);
$mockMattermost->expects($this->once())
->method('sendMessage')
->with("Test message");
$this->container->set(MattermostService::class, $mockMattermost);
How can I help you explore Laravel packages today?