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 Laravel Package

sylius/resource

Sylius Resource is a lightweight foundation for building domain resources in Symfony apps. It provides resource configuration, controllers, repositories, events, and form/grid integration to speed up CRUD and admin tooling while keeping your domain and persistence clean.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require sylius/resource
    

    No additional configuration is required for basic usage.

  2. First Use Case: Defining a Resource Create a simple resource class (e.g., Post) extending Sylius\Component\Resource\Model\ResourceInterface and implement ResourceInterface:

    namespace App\Entity;
    
    use Sylius\Component\Resource\Model\ResourceInterface;
    
    class Post implements ResourceInterface
    {
        // Your properties (e.g., id, title, content)
    }
    
  3. Registering the Resource Define a Resource class in config/packages/sylius_resource.yaml:

    sylius_resource:
        resources:
            app.post:
                driver: doctrine/orm
                classes:
                    model: App\Entity\Post
    
  4. Basic CRUD Operations Use the ResourceRepository and ResourceRegistry services:

    use Sylius\Component\Resource\Repository\RepositoryInterface;
    use Sylius\Component\Resource\ResourceRegistryInterface;
    
    class PostController extends AbstractController
    {
        public function index(ResourceRegistryInterface $registry)
        {
            $repository = $registry->getRepository('app.post');
            $posts = $repository->findAll();
            return $this->render('posts/index.html.twig', ['posts' => $posts]);
        }
    }
    

Implementation Patterns

1. Resource Definition & Configuration

  • Multi-Driver Support: Configure resources for Doctrine ORM, Doctrine DBAL, or Propel:
    sylius_resource:
        resources:
            app.post:
                driver: doctrine/orm
                classes:
                    model: App\Entity\Post
                    repository: App\Repository\PostRepository
                    form: App\Form\PostType
    
  • Custom Repositories: Extend Sylius\Component\Resource\Repository\RepositoryInterface for custom logic.

2. Dependency Injection & Services

  • ResourceRegistry: Centralized access to all resources:
    $post = $registry->getRepository('app.post')->find(1);
    
  • ResourceFactory: Create new resource instances:
    $post = $registry->getFactory('app.post')->createNew();
    

3. Forms & Validation

  • Automatic Form Binding: Use ResourceFormFactory to generate forms tied to your resource:
    $form = $this->createForm(
        $registry->getFormType('app.post'),
        $post
    );
    
  • Validation: Leverage Symfony’s validator with your resource entities.

4. Event-Driven Workflows

  • Lifecycle Events: Subscribe to resource events (e.g., ResourceCreated, ResourceUpdated):
    use Sylius\Component\Resource\Model\ResourceInterface;
    use Sylius\Component\Resource\ResourceEvents;
    
    $dispatcher->addListener(ResourceEvents::RESOURCE_CREATED, function (ResourceEvent $event) {
        $resource = $event->getSubject();
        // Custom logic on creation
    });
    

5. API & Serialization

  • API Platform Integration: Use ResourceInterface with API Platform’s ResourceInterface for automatic API generation.
  • Custom Serialization: Implement JsonSerializable or use Symfony’s serializer with your resource entities.

Gotchas and Tips

Pitfalls

  1. Driver Mismatches

    • Ensure the driver in your config matches the actual database layer (e.g., doctrine/orm vs. doctrine/dbal).
    • Fix: Verify your EntityManager or Connection is properly configured.
  2. Circular Dependencies

    • Avoid circular references between resources (e.g., Post has Author, Author has Post).
    • Fix: Use lazy loading or DTOs for complex relationships.
  3. Repository Overrides

    • Custom repositories must implement RepositoryInterface; otherwise, they won’t be autowired.
    • Fix: Extend Sylius\Component\Resource\Repository\RepositoryInterface:
      class PostRepository extends AbstractRepository implements RepositoryInterface
      
  4. Form Type Conflicts

    • If multiple resources share the same form type name, the last defined one in the config will override others.
    • Fix: Use unique form type names (e.g., app.post_form).
  5. Event Dispatching

    • Events are dispatched after the resource is persisted. For pre-persistence logic, use Symfony’s PRE_PERSIST/PRE_UPDATE events.
    • Fix: Combine with Doctrine lifecycle callbacks if needed.

Debugging Tips

  • Check Registered Resources:
    $resources = $registry->getAllResourceNames();
    // ['app.post', 'app.author']
    
  • Inspect Resource Config:
    $config = $registry->getConfiguration('app.post');
    
  • Enable Debug Mode: Set SYLIUS_RESOURCE_DEBUG=true in your .env to log resource-related operations.

Extension Points

  1. Custom Drivers Implement Sylius\Component\Resource\Driver\DriverInterface for non-Doctrine storage (e.g., Elasticsearch, MongoDB).

  2. Dynamic Resource Loading Use ResourceRegistryInterface::getAllResourceNames() to dynamically load resources based on user roles or other conditions.

  3. Bulk Operations Combine with Doctrine’s BulkOperations or QueryBuilder for batch updates/deletes:

    $qb = $repository->createQueryBuilder('p');
    $qb->delete('p', 'p')->where('p.published = :val')->setParameter('val', false);
    $qb->getQuery()->execute();
    
  4. Soft Deletes Extend your resource model to support soft deletes:

    use Gedmo\Timestampable\Traits\TimestampableEntity;
    
    class Post implements ResourceInterface
    {
        use TimestampableEntity;
        private ?\DateTimeInterface $deletedAt = null;
    }
    

    Then configure Doctrine’s SoftDeleteable listener.

  5. Translation Support Use gedmo/translatable with Sylius Resource for multilingual fields:

    sylius_resource:
        resources:
            app.post:
                classes:
                    model: App\Entity\Post
                    translation: App\Entity\PostTranslation
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor