btba/chat-bundle
Symfony bundle providing a simple chat service with configurable refresh interval and Doctrine entities for authors and messages. Install via Composer, register the bundle, add YAML config and routes, and extend base models to persist chat data.
Installation:
composer require btba/chat-bundle
Register the bundle in config/bundles.php:
Btba\ChatBundle\BtbaChatBundle::class => ['all' => true]
Configuration:
Create config/packages/btba_chat.yaml:
btba_chat:
update_interval: 1000
message_class: App\Entity\ChatMessage
author_class: App\Entity\User
Routes:
Add to config/routes/btba_chat.yaml:
btba_chat:
resource: '@BtbaChatBundle/Resources/config/routes.yaml'
prefix: /chat
Entities:
Extend BaseAuthor and BaseChatMessage in your User and ChatMessage entities (see README).
Repository:
Add MessageQuery trait to your ChatMessageRepository.
Assets:
Import CSS/JS in app.css/app.js:
@import '../../vendor/btba/chat-bundle/assets/css/chat.css';
import * as chat from '../../vendor/btba/chat-bundle/assets/js/chat';
Render Chat: Add to your Twig template:
{{ render(controller('Btba\\ChatBundle\\Controller\\ChatController::show')) }}
Real-Time Updates:
The update_interval (default: 1000ms) controls how often the chat polls for new messages. Use AJAX to fetch updates via the bundle’s API (e.g., /chat/messages).
Message Handling:
submitChat JS function to POST messages to /chat/send.
Example:
chat.submitChat(e, { content: "Hello!", authorId: 1 });
resources/views/chat/index.html.twig) to customize rendering.User Integration:
{{ app.user }} in Twig).chat.setCurrentUser({{ app.user.id }});
Database Operations:
ChatMessageRepository to query messages (e.g., findByDate()).$messages = $this->getDoctrine()
->getRepository('App:ChatMessage')
->findBy([], ['date' => 'ASC']);
Event Listeners:
Trigger custom logic on message creation by extending the bundle’s events (e.g., MessageSentEvent). Override the bundle’s event dispatcher in your services.yaml:
services:
App\EventListener\ChatListener:
tags:
- { name: kernel.event_listener, event: btba_chat.message_sent, method: onMessageSent }
Frontend Frameworks:
Replace jQuery with Vue/React by rewriting chat.js to use your framework’s HTTP client (e.g., axios).
Example Vue integration:
methods: {
sendMessage() {
axios.post('/chat/send', { content: this.message, authorId: this.userId })
.then(response => this.messages.push(response.data));
}
}
WebSockets:
Replace polling with Mercure or Pusher by extending the ChatController to broadcast messages via WebSocket.
Permissions:
Restrict message access in ChatController:
public function showAction(Request $request)
{
$this->denyAccessUnlessGranted('CHAT_VIEW', $request->getUser());
// ...
}
Testing:
Mock the MessageQuery trait in PHPUnit:
$repository = $this->createMock(ChatMessageRepository::class);
$repository->method('findByDate')->willReturn([$mockMessage]);
$this->container->set('App:ChatMessage', $repository);
Entity Mismatch:
Class "App\Entity\ChatMessage" is not a valid entity or extends BaseChatMessage.ChatMessage extends Btba\ChatBundle\Model\BaseChatMessage and includes all required fields (content, date, author).Route Conflicts:
No route found for "GET /chat".prefix in btba_chat.yaml matches your routes file and is loaded after other bundles.JavaScript Errors:
chat is not defined.chat.js is imported after jQuery (if used) and the DOM is ready:
document.addEventListener('DOMContentLoaded', () => {
import * as chat from '...';
});
Polling Overhead:
update_interval causes lag or excessive DB queries.3000) or implement server-sent events (SSE).Circular Dependencies:
Class "App\Entity\User" uses a non-existent property "messages".// User.php
private $messages;
// ChatMessage.php
private $author;
Log Messages:
Enable Symfony’s profiler to inspect ChatController responses:
// config/packages/dev/btba_chat.yaml
btba_chat:
debug: true
Database Queries: Use Doctrine’s query logging:
$this->getDoctrine()->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
Event Debugging: Dump events in a listener:
public function onMessageSent(MessageSentEvent $event) {
dump($event->getMessage());
}
Custom Templates:
Override the default Twig template by copying BtbaChatBundle:Chat:index.html.twig to templates/chat/index.html.twig.
Message Validation:
Extend the bundle’s validator by adding constraints to your ChatMessage entity:
use Symfony\Component\Validator\Constraints as Assert;
/**
* @Assert\NotBlank
* @Assert\Length(max=1000)
*/
protected $content;
API Endpoints:
Add custom endpoints by extending ChatController:
class CustomChatController extends ChatController {
public function customAction() {
return $this->json(['status' => 'ok']);
}
}
Register the route in btba_chat.yaml:
custom_chat:
path: /chat/custom
controller: App\Controller\CustomChatController::customAction
Message Storage:
Replace Doctrine with another ORM (e.g., MongoDB) by implementing MessageQuery for your repository.
UI Components:
Replace the default chevron/toggle logic by extending the chat.js module:
chat.changeChevron = function(element) {
// Custom logic
};
How can I help you explore Laravel packages today?