Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

yoeriboven's avatar

Add items to custom collection

I'm building a custom collection class called Plans.

<?php

namespace App\Plans;

use Illuminate\Support\Collection;

class Plans extends Collection
{
  public function withStripeId(string $stripeId) {
    ...
  }
}

Plans has a few custom methods (like retrieving by stripe id) and should contain an object of each of my Plan classes.

It should be retrievable from the service container with the Plan objects already in it.

Illuminate\Support\Collection has an $items property but I can't instantiate the Plan objects there.

Is overriding the constructor my best bet here?

0 likes
2 replies
yoeriboven's avatar

A bit too quick with posting a question here.

I didn't want to override the constructor because what happens when the constructor on the underlying class changes? I'd always have to check that class to see if something changed.

Then I remembered I could just call the constructor by myself like this:

public function __construct($items = [])
{
  $plans = [
    new ProPlan(),
    new AgencyPlan()
  ];

  parent::__construct($plans);
}
yoeriboven's avatar
yoeriboven
OP
Best Answer
Level 13

Now, I realize this doesn't work.

Every time you call a function on the collection a new one is returned using this constructor.

A better solution is to create a static constructor:

public static function withPlans()
{
    $plans = [
        new ProPlan(),
        new AgencyPlan(),
    ];

    return new static($plans);
}

Please or to participate in this conversation.