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

Collection Laravel Package

cvek/collection

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require cvek/collection
    

    Ensure symfony/property-access is also installed (dependency).

  2. Basic Usage

    use Cvek\Collection\Collection;
    use Symfony\Component\PropertyAccess\PropertyAccess;
    
    $propertyAccessor = PropertyAccess::createPropertyAccessor();
    $collection = new Collection([1, 2, 3], $propertyAccessor);
    
    // Use Laravel Collection methods
    $first = $collection->first(); // 1
    $count = $collection->count(); // 3
    
    // Access nested properties (Symfony-style)
    $userCollection = new Collection([['name' => 'John', 'address' => ['city' => 'NY']]], $propertyAccessor);
    $city = $userCollection->first()->getValue('address.city'); // 'NY'
    
  3. First Use Case Replace Symfony’s native arrays or ArrayCollection with Laravel’s Collection for:

    • Familiar fluent syntax (pluck(), where(), groupBy()).
    • Seamless integration with Laravel’s ecosystem (e.g., Eloquent relationships).
    • Accessing private/virtual properties via Symfony’s PropertyAccess.

Implementation Patterns

Workflows

  1. Property Access Workflow

    $collection = new Collection([$user], $propertyAccessor);
    $name = $collection->first()->getValue('privateProperty'); // Works with private props
    $virtual = $collection->first()->getValue('virtualProperty'); // Works with virtual props
    
  2. Hybrid Collections Merge Symfony’s PropertyAccess with Laravel’s Collection methods:

    $items = $collection
        ->filter(fn($item) => $item->getValue('isActive'))
        ->pluck('name')
        ->all();
    
  3. Integration with Symfony Forms

    // In a Symfony FormType
    $choices = new Collection([$entity1, $entity2], $propertyAccessor);
    $builder->add('items', ChoiceType::class, [
        'choices' => $choices->pluck('id', 'name')->toArray(),
    ]);
    
  4. Dynamic Property Handling Use getValue()/setValue() for dynamic property access:

    $collection->first()->setValue('dynamicProp', 'value');
    $value = $collection->first()->getValue('dynamicProp');
    

Tips for Smooth Integration

  • Lazy Property Access: Defer property access until needed (e.g., in map() or each()).
  • Fallback to Native Methods: Use ->toArray() or ->toNative() when Symfony-specific logic is required.
  • Dependency Injection: Bind PropertyAccess to a service in Symfony’s container for reuse:
    # config/services.yaml
    services:
        Symfony\Component\PropertyAccess\PropertyAccess: ~
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Symfony’s PropertyAccess adds reflection overhead. Avoid deep property chains in performance-critical loops.
    • Mitigation: Cache property access paths or use native methods where possible.
  2. Method Conflicts

    • Laravel’s Collection and Symfony’s ArrayCollection share method names (e.g., count()). Prefix Symfony methods with _symfony if needed:
      $collection->_symfonyCount(); // Explicit call to Symfony's count()
      
  3. Immutable Collections

    • The adapter doesn’t enforce immutability. Use Collection::make() with immutable() if needed:
      $immutable = Collection::make([1, 2, 3], $propertyAccessor)->immutable();
      
  4. Virtual Properties

    • Virtual properties require Symfony’s PropertyAccess to be configured with a PropertyAccessorBuilder. Ensure your builder supports them:
      $builder = PropertyAccess::createPropertyAccessorBuilder();
      $builder->enableMagicAccess(); // For virtual properties
      $accessor = $builder->getPropertyAccessor();
      

Debugging

  • Property Access Errors: Use try-catch with PropertyAccessException:
    try {
        $value = $collection->first()->getValue('invalid.path');
    } catch (\Symfony\Component\PropertyAccess\Exception\PropertyAccessException $e) {
        // Handle gracefully
    }
    
  • Method Introspection: Check available methods with:
    get_class_methods($collection); // Laravel methods
    $collection->getPropertyAccessor()->getProperty($object, 'path'); // Symfony introspection
    

Extension Points

  1. Custom Property Accessors Extend Cvek\Collection\Collection to support custom access logic:

    class CustomCollection extends Collection {
        public function getValue($property) {
            // Custom logic
            return parent::getValue($property);
        }
    }
    
  2. Integration with Doctrine Use the adapter to bridge Doctrine entities and Laravel Collections:

    $entities = $entityManager->getRepository(Entity::class)->findAll();
    $collection = new Collection($entities, $propertyAccessor);
    $ids = $collection->pluck('id')->toArray();
    
  3. Event Listeners Attach listeners to property access events (via Symfony’s PropertyAccess events):

    $propertyAccessor->addPropertyListener('entity.property', 'onAccess');
    
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony