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

Sonata News Bundle Laravel Package

awaresoft/sonata-news-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation via Composer (if not symlinked):

    composer require awaresoft/sonata-news-bundle
    

    Note: Follow the README instructions for symlinking if modifying locally.

  2. Enable the Bundle in config/bundles.php:

    return [
        // ...
        Awaresoft\SonataNewsBundle\SonataNewsBundle::class => ['all' => true],
    ];
    
  3. Run Migrations (if using Doctrine):

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  4. Basic Routing in config/routes.yaml:

    sonata_news:
        resource: "@SonataNewsBundle/Resources/config/routing/all.xml"
        prefix: /news
    
  5. First Use Case:

    • Create a news entity via admin interface (if SonataAdminBundle is integrated).
    • Display a list of news items in a template:
      {% for news in sonata_news_list %}
          <h2>{{ news.title }}</h2>
          <p>{{ news.content|truncate(200) }}</p>
      {% endfor %}
      

Implementation Patterns

Core Workflows

  1. Admin Integration:

    • Extend SonataAdminBundle to manage news entities:
      // src/Admin/NewsAdmin.php
      use Awaresoft\SonataNewsBundle\Admin\NewsAdmin as BaseNewsAdmin;
      
      class NewsAdmin extends BaseNewsAdmin {
          protected function configureListFields(ListMapper $listMapper) {
              $listMapper->add('title');
              $listMapper->add('createdAt');
          }
      }
      
  2. Custom News Types:

    • Override the default News entity:
      // src/Entity/News.php
      use Awaresoft\SonataNewsBundle\Entity\News as BaseNews;
      
      class News extends BaseNews {
          /**
           * @ORM\Column(type="string", length=255, nullable=true)
           */
          private $customField;
      }
      
  3. API Endpoints:

    • Use Symfony’s serializer to expose news data:
      // src/Controller/NewsController.php
      use Awaresoft\SonataNewsBundle\Entity\NewsRepository;
      
      class NewsController extends AbstractController {
          public function list(NewsRepository $repo): JsonResponse {
              return $this->json($repo->findAll());
          }
      }
      
  4. Frontend Display:

    • Twig extensions for filtering/sorting:
      {{ sonata_news_list({
          'filter': 'published',
          'sort': 'createdAt',
          'direction': 'desc'
      }) }}
      
  5. Event Listeners:

    • Hook into news lifecycle events (e.g., news.publish):
      // src/EventListener/NewsListener.php
      use Awaresoft\SonataNewsBundle\Event\NewsEvent;
      
      class NewsListener {
          public function onNewsPublish(NewsEvent $event) {
              // Send notification, log, etc.
          }
      }
      

Gotchas and Tips

Pitfalls

  1. Symfony 2.x Dependency:

    • The bundle is locked to Symfony 2.x. Avoid mixing with Symfony 4/5/6 without forking.
    • Workaround: Use a wrapper bundle or polyfill compatibility layer.
  2. Doctrine ORM Assumptions:

    • Assumes createdAt and updatedAt fields exist on the News entity. Override the entity if missing:
      use Gedmo\Mapping\Annotation as Gedmo;
      
      /**
       * @Gedmo\Timestampable(on="create")
       */
      private $createdAt;
      
  3. Admin Bundle Dependency:

    • Relies on SonataAdminBundle for CRUD. If not using SonataAdmin, manually implement controllers/repositories.
  4. Routing Conflicts:

    • The all.xml routes may clash with existing routes. Override in routing.yml:
      sonata_news_list:
          path: /custom-news
          defaults: { _controller: sonata_news.controller.list }
      
  5. Translation Quirks:

    • Hardcoded strings in templates (e.g., "News"). Override via translation files or Twig filters:
      {{ 'News'|trans }}
      

Debugging Tips

  1. Enable Debug Mode:

    APP_DEBUG=1 php bin/console cache:clear
    
  2. Check Event Dispatching:

    • Verify listeners are subscribed in services.yaml:
      services:
          App\EventListener\NewsListener:
              tags:
                  - { name: kernel.event_listener, event: sonata.news.publish, method: onNewsPublish }
      
  3. Database Schema:

    • Dump schema to compare with expected structure:
      php bin/console doctrine:schema:update --dump-sql
      

Extension Points

  1. Custom Repositories:

    • Extend NewsRepository for complex queries:
      class CustomNewsRepository extends NewsRepository {
          public function findByCategory(string $category) {
              return $this->createQueryBuilder('n')
                  ->where('n.category = :category')
                  ->setParameter('category', $category)
                  ->getQuery()
                  ->getResult();
          }
      }
      
  2. Form Overrides:

    • Customize the news creation form:
      // src/Form/NewsType.php
      use Awaresoft\SonataNewsBundle\Form\Type\NewsType as BaseNewsType;
      
      class NewsType extends BaseNewsType {
          public function buildForm(FormBuilderInterface $builder, array $options) {
              parent::buildForm($builder, $options);
              $builder->add('customField');
          }
      }
      
  3. Twig Global Variables:

    • Pass custom data to all templates:
      // src/Twig/AppExtension.php
      class AppExtension extends \Twig\Extension\AbstractExtension {
          public function getGlobals() {
              return [
                  'custom_news_config' => ['max_items' => 10],
              ];
          }
      }
      
  4. Asset Management:

    • Override bundle assets (CSS/JS) by copying files to public/bundles/sonatanews/ and modifying.
  5. Security:

    • Secure routes with voter logic:
      // src/Security/Voter/NewsVoter.php
      use Awaresoft\SonataNewsBundle\Entity\NewsInterface;
      
      class NewsVoter extends AbstractVoter {
          protected function supports(string $attribute, $subject): bool {
              return $subject instanceof NewsInterface;
          }
      }
      
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