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

Reference Peels Laravel Package

baks-dev/reference-peels

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require baks-dev/reference-peels
    

    Ensure your composer.json has PHP 8.4+ constraints.

  2. First Use Case: Peel a reference (e.g., a database record or API response) by wrapping it in a Peel class:

    use BaksDev\ReferencePeels\Peel;
    
    $data = ['id' => 1, 'name' => 'Test'];
    $peeled = Peel::make($data);
    

    The package abstracts "peeling" (stripping metadata or transforming data) via a fluent interface.

  3. Key Classes:

    • Peel: Core class for peeling operations.
    • PeelCollection: For peeling arrays/collections.
    • Peelable: Trait for Eloquent models or custom classes to enable peeling.
  4. Where to Look First:

    • Peel Class Docs (if available).
    • config/reference-peels.php for default behaviors (e.g., allowed peel methods).
    • tests/ for usage examples (if tests exist).

Implementation Patterns

Common Workflows

  1. Peeling Eloquent Models:

    use BaksDev\ReferencePeels\Peelable;
    
    class User extends Model implements Peelable {
        // Model logic...
    }
    
    $user = User::find(1);
    $peeled = $user->peel(['id', 'name']); // Returns stripped data.
    
  2. Custom Peel Methods: Extend the Peel class to add domain-specific peeling logic:

    class CustomPeel extends Peel {
        public function peelUserData(array $data): array {
            return [
                'id' => $data['id'],
                'email' => $data['email'] ?? null,
            ];
        }
    }
    
  3. API Response Handling: Peel API responses before returning them to clients:

    $response = $apiClient->get('/users/1');
    $peeledResponse = Peel::make($response->data)->peel(['id', 'name', 'created_at']);
    return response()->json($peeledResponse);
    
  4. Batch Peeling: Use PeelCollection for arrays or collections:

    $users = User::all();
    $peeledUsers = PeelCollection::make($users)
        ->peel(['id', 'name'])
        ->toArray();
    
  5. Middleware for Peeling: Create middleware to peel responses globally:

    namespace App\Http\Middleware;
    
    use BaksDev\ReferencePeels\Peel;
    use Closure;
    
    class PeelResponseMiddleware {
        public function handle($request, Closure $next) {
            $response = $next($request);
            if ($response->isJson()) {
                $data = $response->getData();
                $peeled = Peel::make($data)->peel(config('reference-peels.default_fields'));
                $response->setData($peeled);
            }
            return $response;
        }
    }
    
  6. Service Provider Integration: Bind the Peel class to the container in AppServiceProvider:

    public function register() {
        $this->app->singleton(Peel::class, function () {
            return new Peel(config('reference-peels'));
        });
    }
    

Gotchas and Tips

Pitfalls

  1. Over-Peeling:

    • Issue: Peeling too aggressively can strip critical data (e.g., id for relationships).
    • Fix: Use whitelists (e.g., peel(['id', 'name'])) instead of blacklists.
  2. Performance with Large Data:

    • Issue: Peeling nested arrays/collections recursively can be slow.
    • Fix: Limit depth or use Peel::shallow() for top-level peeling.
  3. Type Safety:

    • Issue: The package assumes arrays/objects. Passing non-peelable data (e.g., null) may throw errors.
    • Fix: Add guards:
      if (!is_array($data) && !method_exists($data, 'toArray')) {
          return $data; // or throw custom exception
      }
      
  4. Configuration Overrides:

    • Issue: Default peel methods in config/reference-peels.php may conflict with custom logic.
    • Fix: Merge configs explicitly:
      $peel = new Peel(array_merge(config('reference-peels'), ['custom_method' => true]));
      
  5. Eloquent Relationships:

    • Issue: Peeling a model with lazy-loaded relationships may trigger N+1 queries.
    • Fix: Eager-load relationships before peeling:
      $user = User::with('posts')->find(1);
      $peeled = $user->peel(['id', 'posts.title']);
      

Debugging Tips

  1. Enable Logging: Add debug output to the Peel class to trace peeled fields:

    Peel::debug(true); // Logs peeled fields to Laravel logs.
    
  2. Test Edge Cases:

    • Empty arrays: Peel::make([])->peel(['id']).
    • Non-array objects: Peel::make(new stdClass())->peel(['prop']).
    • Circular references: Use Peel::make($data)->peel(['id'])->withoutCircular().
  3. Check for Deprecations: Monitor the 7.x branch for breaking changes (e.g., method signatures).

Extension Points

  1. Custom Peel Strategies: Implement BaksDev\ReferencePeels\Contracts\PeelStrategy for domain-specific logic:

    class ApiPeelStrategy implements PeelStrategy {
        public function peel(array $data, array $fields): array {
            return array_intersect_key($data, array_flip($fields));
        }
    }
    
  2. Event Listeners: Trigger events before/after peeling:

    Peel::peeling(function ($data, $fields) {
        // Pre-peel logic (e.g., sanitize fields).
    });
    
    Peel::peeled(function ($peeledData, $originalData, $fields) {
        // Post-peel logic (e.g., log changes).
    });
    
  3. Macros: Extend Peel with macros for reusable logic:

    Peel::macro('audit', function ($fields) {
        $peeled = $this->peel($fields);
        Log::info("Peeled fields: " . implode(', ', $fields));
        return $peeled;
    });
    
  4. Testing: Mock the Peel class in tests:

    $mockPeel = Mockery::mock(Peel::class);
    $mockPeel->shouldReceive('peel')->andReturn(['id' => 1]);
    $this->app->instance(Peel::class, $mockPeel);
    
  5. Performance Optimization: Cache peeled results for immutable data:

    $peeled = Peel::make($data)->peel(['id'])->remember(60); // Cache for 60s.
    
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.
terminal42/code-quality-tools
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