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

Resource Bundle Laravel Package

sylius/resource-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require sylius/resource-bundle
    

    Enable it in config/bundles.php:

    return [
        // ...
        Sylius\ResourceBundle\SyliusResourceBundle::class => ['all' => true],
    ];
    
  2. Define a Resource Annotate your entity with @AsResource (or use the attribute [AsResource] in PHP 8+):

    use Sylius\Component\Resource\Model\ResourceInterface;
    use Sylius\ResourceBundle\Annotation\AsResource;
    
    #[AsResource]
    class Product implements ResourceInterface
    {
        // Your entity properties
    }
    
  3. Configure the Resource Define the resource in config/packages/sylius_resource.yaml:

    sylius_resource:
        resources:
            App\Entity\Product:
                driver: doctrine/orm
                repository:
                    type: doctrine
                    class: App\Repository\ProductRepository
                factory:
                    type: doctrine
                    class: App\Factory\ProductFactory
                form: App\Form\ProductType
    
  4. Generate Basic CRUD Use the sylius:resource:generate command to scaffold controllers and routes:

    php bin/console sylius:resource:generate App\Entity\Product
    
  5. First Use Case Access the generated routes (e.g., /api/products for listing, /api/products/{id} for detail) or integrate with your frontend.


Implementation Patterns

Core Workflows

1. Resource Definition and Configuration

  • Driver Flexibility: Use doctrine/orm, doctrine/mongodb, or custom drivers via driver: { type: custom, class: MyCustomDriver }.
  • Repository Customization: Extend the default repository to add custom methods:
    class ProductRepository extends ServiceEntityRepository
    {
        public function findByActive(bool $active): array
        {
            return $this->createQueryBuilder('p')
                ->andWhere('p.active = :active')
                ->setParameter('active', $active)
                ->getQuery()
                ->getResult();
        }
    }
    
  • Factory Patterns: Implement custom factories for complex object creation:
    class ProductFactory implements FactoryInterface
    {
        public function createNew(): Product
        {
            return new Product();
        }
    }
    

2. Controller Integration

  • Base Controller: Extend AbstractResourceController for shared logic:
    use Sylius\Bundle\ResourceBundle\Controller\AbstractResourceController;
    
    class ProductController extends AbstractResourceController
    {
        protected function configureActions(Actions $actions): Actions
        {
            return $actions
                ->index()
                ->create()
                ->update()
                ->delete();
        }
    }
    
  • Custom Actions: Add custom operations (e.g., bulk actions):
    # config/packages/sylius_resource.yaml
    sylius_resource:
        resources:
            App\Entity\Product:
                actions:
                    bulk_delete: true
    

3. Request Handling

  • Filtering: Use query parameters for filtering (e.g., ?active=true):
    // In your repository
    public function createQueryBuilder(string $alias, ?string $indexBy = null): QueryBuilder
    {
        $qb = parent::createQueryBuilder($alias, $indexBy);
        $active = $this->getRequest()->query->get('active');
        if ($active !== null) {
            $qb->andWhere("p.active = :active")->setParameter('active', $active);
        }
        return $qb;
    }
    
  • Sorting: Support dynamic sorting via ?sort=-createdAt:
    sylius_resource:
        resources:
            App\Entity\Product:
                sorting:
                    createdAt: ~
                    name: ~
    

4. State Machines

  • Configure Transitions: Use Symfony’s state machine component:
    sylius_resource:
        resources:
            App\Entity\Product:
                state_machine:
                    machine: product_state_machine
                    transition: publish
    
  • Custom Guards: Add logic to validate transitions:
    use Sylius\Component\Resource\StateMachine\Guard\GuardInterface;
    
    class PublishGuard implements GuardInterface
    {
        public function supports(object $object, string $transition): bool
        {
            return $object instanceof Product && $object->isReadyToPublish();
        }
    }
    

5. API Integration

  • Serialization: Use JMS Serializer or Symfony Serializer for API responses:
    sylius_resource:
        resources:
            App\Entity\Product:
                serialization:
                    groups: ['api']
    
  • Pagination: Leverage Pagerfanta for paginated responses:
    use Pagerfanta\Pagerfanta;
    
    public function indexAction(Request $request): Response
    {
        $pager = new Pagerfanta(new ArrayAdapter($this->repository->findAll()));
        $pager->setMaxPerPage(10);
        $pager->setCurrentPage($request->query->getInt('page', 1));
        return $this->handleView($this->view($pager, 200));
    }
    

6. Event-Driven Extensions

  • Listeners: Subscribe to resource events (e.g., pre_create, post_update):
    use Sylius\Component\Resource\Model\ResourceInterface;
    use Sylius\Component\Resource\ResourceEvents;
    
    $eventDispatcher->addListener(ResourceEvents::PRE_CREATE, function (ResourceEvent $event) {
        if ($event->getSubject() instanceof Product) {
            $event->getSubject()->setCreatedBy($this->getUser());
        }
    });
    
  • Flash Messages: Add feedback via events:
    $eventDispatcher->addListener(ResourceEvents::POST_CREATE, function (ResourceEvent $event) {
        $this->addFlash('success', 'Product created successfully!');
    });
    

Integration Tips

  1. Doctrine Attributes: Use Doctrine’s attributes (e.g., [ORM\Entity], [ORM\Table]) alongside AsResource for cleaner annotations.

  2. Symfony UX: Combine with Symfony UX for reactive forms:

    use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
    
    #[AsLiveComponent('product_form')]
    class ProductFormType extends AbstractType
    {
        // ...
    }
    
  3. Testing: Use the sylius:resource:debug command to inspect resource configurations:

    php bin/console sylius:resource:debug App\Entity\Product
    
  4. Validation: Integrate with Symfony Validator for form validation:

    use Symfony\Component\Validator\Constraints as Assert;
    
    class Product
    {
        #[Assert\NotBlank]
        private string $name;
    }
    
  5. API Platform: For API-first projects, pair with API Platform for automatic API generation:

    # config/packages/api_platform.yaml
    api_platform:
        formats:
            jsonld:
                mime_types: ['application/ld+json']
        patch_formats:
            json: true
    

Gotchas and Tips

Pitfalls

  1. Route Conflicts:

    • Issue: Default routes (e.g., DELETE /products/{id}) may conflict with other bundles.
    • Fix: Customize route names in configuration:
      sylius_resource:
          resources:
              App\Entity\Product:
                  route_name_prefix: api_products
      
  2. Circular Dependencies:

    • Issue: Factories or repositories may cause circular references if not careful.
    • Fix: Use lazy loading or interfaces to decouple dependencies:
      interface ProductRepositoryInterface extends RepositoryInterface
      {
          // ...
      }
      
  3. State Machine Mismatches:

    • Issue: State machine transitions may fail if guards or machines are misconfigured.
    • Fix: Debug with:
      php bin/console debug:state-machine App\Entity\Product
      
  4. Pagination Limits:

    • Issue: Default pagination limits may cause performance issues.
    • Fix: Override in your controller or repository:
      $pager->setMaxPerPage(50); // Adjust as needed
      
  5. Form Parameter Bags:

    • Issue: Nested forms may fail due to parameter bag access.
    • Fix: Ensure proper form type configuration:
      class ProductType extends AbstractType
      {
          public function buildForm(FormBuilderInterface $builder, array $options)
          {
              $builder->add('images', CollectionType::class, [
                  'entry_type' => ImageType::class,
                  'allow_add' => true,
                  'allow_delete' => true,
                  'by_reference' => false,
              ]);
          }
      }
      
  6. **Doctrine Event List

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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle