Asara
Asara

Reputation: 3374

Doctrine arrayCollection check if members are instanceof

When I declare a method I declare the type of an argument:

public function doOnce(CoolParam $param) {...}

But when I have a Doctrine ArrayCollection I can only check for the array

public function doOMulti(ArrayCollection $params) {...}

Now I would like to be sure, that all members of ArrayCollection are instance of CoolParam. Therefore I can loop the whole Array and check with $param instanceof CoolParam.

But is there a way to use a ArrayCollection method for this case? Just something like

$params->membersAreInstanceOf('CoolParam');

Upvotes: 0

Views: 528

Answers (1)

StuBez
StuBez

Reputation: 1364

One option would be to use the ArrayCollection inside of another class to enforce the type of the elements in the collection.

For example

class UsersCollection
{
    private $users;

    public function __construct()
    {
        $this->users = new ArrayCollection();
    }

    public function addUser(User $user)
    {
        $this->users->add($user);
    }
}

You would then know that all elements in public function doOMulti(UsersCollection $params) {...} will be of the correct type.

Upvotes: 1

Related Questions