Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Comment Bundle Laravel Package

altblock/comment-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require altblock/comment-bundle
    

    Run bundle installation command:

    php bin/console fos:comment:install
    

    This generates the required database tables (if using Doctrine) and config files.

  2. Enable the Bundle: Add to config/bundles.php:

    return [
        // ...
        AltBlock\CommentBundle\AltBlockCommentBundle::class => ['all' => true],
    ];
    
  3. First Use Case: Display comments on a page:

    {% render 'AltBlockCommentBundle:Comment:thread.html', {
        'subject': commentableEntity,
        'template': 'AltBlockCommentBundle:Comment:thread.html.twig'
    } %}
    

    Ensure your entity is annotated with @Commentable:

    use AltBlock\CommentBundle\Model\CommentableInterface;
    use Doctrine\ORM\Mapping as ORM;
    
    /**
     * @ORM\Entity
     * @ORM\Table(name="blog_posts")
     */
    class BlogPost implements CommentableInterface
    {
        // ...
    }
    

Implementation Patterns

Core Workflows

  1. Comment Submission: Use the fos_comment_form type in Symfony forms:

    $form = $this->createFormBuilder($comment)
        ->add('content', 'fos_comment_text', [
            'attr' => ['class' => 'form-control']
        ])
        ->getForm();
    

    Submit via a controller:

    $comment = new Comment();
    $comment->setSubject($commentableEntity);
    $form->handleRequest($request);
    if ($form->isValid()) {
        $em->persist($comment);
        $em->flush();
    }
    
  2. Thread Rendering: Customize the thread template by extending:

    {% extends 'AltBlockCommentBundle:Comment:thread.html.twig' %}
    {% block comment_content %}
        {{- comment.content -}}
        {% if comment.author %}
            <small>By {{ comment.author.username }}</small>
        {% endif %}
    {% endblock %}
    
  3. API Integration (FOSRestBundle): Enable REST API by configuring routing:

    # config/routes.yaml
    fos_comment_rest:
        resource: "@AltBlockCommentBundle/Resources/config/routing/rest.xml"
        prefix: /api/comments
    

    Access endpoints like /api/comments/{subject}.

  4. Event-Driven Extensions: Subscribe to lifecycle events (e.g., fos_comment_pre_persist):

    // src/EventListener/CommentListener.php
    public function onPrePersist(PrePersistCommentEvent $event)
    {
        $comment = $event->getComment();
        $comment->setIpAddress($event->getRequest()->getClientIp());
    }
    

    Register in services.yaml:

    services:
        App\EventListener\CommentListener:
            tags:
                - { name: kernel.event_listener, event: fos_comment_pre_persist, method: onPrePersist }
    

Integration Tips

  1. FOSUserBundle: Link comments to users by implementing CommentableInterface in your user entity:

    class User implements CommentableInterface
    {
        // ...
    }
    

    Configure in config.yml:

    fos_comment:
        db_driver: orm
        class:
            model:
                comment: App\Entity\Comment
                thread: App\Entity\Thread
            form: App\Form\CommentType
        service:
            comment_manager: fos_comment.manager.default
        acl: true  # Enable ACL if using FOSUserBundle
    
  2. Akismet Integration: Enable in config.yml:

    fos_comment:
        akismet:
            enabled: true
            key: "your_akismet_key"
            blog: "your_blog_url"
    
  3. Markup Parsing: Configure HtmlPurifier or php-sundown in config.yml:

    fos_comment:
        markup_parser: htmlpurifier
        htmlpurifier:
            config: "@altblock_comment.htmlpurifier.config"
    
  4. Custom Sorting: Override the default sort order (e.g., by createdAt):

    fos_comment:
        thread_sort:
            method: "createdAt"
            order: DESC
    

Gotchas and Tips

Common Pitfalls

  1. Entity Mapping:

    • Ensure your Comment and Thread entities extend the base classes:
      use AltBlock\CommentBundle\Model\Comment as BaseComment;
      class Comment extends BaseComment { ... }
      
    • Missing @Commentable on entities will break thread rendering.
  2. Database Schema:

    • Run migrations after installation:
      php bin/console doctrine:migrations:diff
      php bin/console doctrine:migrations:migrate
      
    • Custom fields require manual schema updates.
  3. Caching Threads:

    • Thread rendering is cached by default. Clear cache after updates:
      php bin/console cache:clear
      
    • Disable caching in config.yml if needed:
      fos_comment:
          thread_cache: false
      
  4. REST API Quirks:

    • Ensure FOSRestBundle is installed and configured for API routes.
    • Serialization may fail without jms/serializer-bundle:
      composer require jms/serializer-bundle
      

Debugging Tips

  1. Event Debugging:

    • Dump events in listeners:
      public function onPrePersist(PrePersistCommentEvent $event)
      {
          dump($event->getComment(), $event->getRequest());
      }
      
  2. Template Overrides:

    • Use debug:config to verify template paths:
      php bin/console debug:config altblock_comment
      
  3. Acl Issues:

    • If ACL is enabled but not working, check:
      • User roles are properly loaded.
      • fos_comment.acl.provider is configured in security.yml.
  4. Performance:

    • Large threads may cause N+1 queries. Use DQL or repositories to optimize:
      $comments = $commentManager->findCommentsBySubject($subject, 0, 10);
      

Extension Points

  1. Custom Form Fields: Extend the form type:

    class CustomCommentType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->add('rating', 'integer', [
                'label' => 'Rating',
                'attr' => ['class' => 'rating-input']
            ]);
        }
    }
    

    Update config.yml:

    fos_comment:
        class:
            form: App\Form\CustomCommentType
    
  2. Custom Validation: Add constraints to the Comment entity:

    use Symfony\Component\Validator\Constraints as Assert;
    
    class Comment extends BaseComment
    {
        /**
         * @Assert\Length(min=10)
         */
        protected $content;
    }
    
  3. Custom Thread Storage: Implement ThreadManagerInterface for non-Doctrine backends (e.g., MongoDB):

    class MongoThreadManager implements ThreadManagerInterface
    {
        // Implement required methods
    }
    

    Register as a service:

    services:
        fos_comment.manager.thread:
            class: App\Service\MongoThreadManager
            tags:
                - { name: fos_comment.thread_manager }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware