T
T
topuserman2019-09-13 15:45:15
symfony
topuserman, 2019-09-13 15:45:15

Doctrine\Common\Collections, how to remake?

When developing projects, it often becomes necessary for methods to return collections of some objects.
What I ideally need:

  • The base class of a collection that simply knows how to work with any type of data.
  • Be able to type an existing base class (or inherit from the base class of the collection and do the necessary checks for the data type with a little refinement).
  • The collection must implement the Countable , IteratorAggregate , and ArrayAccess interfaces .
  • The ability for a collection to add methods map , filter , etc.

I understand that unfortunately there are no generics in php, and I don’t use Ds\Collection for religious reasons.
Why do I need it:
For example, I threw in a simple interface:
interface GraphInterface {
     public function getPoints() : PointsCollection;
}

  1. The code is easier to read. It is immediately clear what type of objects are in this collection.
  2. If PointsCollection is passed as a parameter to some method, then it is not necessary to check through instanceof every time . It also excludes cases where objects of a different type are included in the collection.
  3. Possibility for each collection to add its own specific methods.
  4. Also, it is more in line with OOP methodology than arrays of objects.

Perhaps you see some hidden problems in this?
What is the complexity, and what does Doctrine\Common\Collections have to do with it:

Difficulties arise with the architecture. I would like to understand how it is better to do typing. My option is to add an abstract getObjectsType() method , which will need to be implemented in each specific collection:
class Point { ... }

class PointCollection extends AbstractCollection {
    protected function getObjectsType() : string {
        return Point::class;
    }
}

Further, when adding objects, check
if(!($this->getObjectsType() instanceof $currentObject)) {
     throw new InvalidArgumentException();
}

What options do you have, and what are their advantages?
I don't use doctrine myself in the project. I came across the implementation of this collection, and really liked the implementation, and the possibilities.
Questions:

Is it possible to use Doctrine\Common\Collections outside of Doctrine, and is it possible to type collections in it and how?
If not, how can I modify this Collections class to satisfy my conditions? Because what methods to add, what to override, what we inherit, what we throw out from the class?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
index0h, 2019-09-13
@index0h

Use the Collection + docblock interface.

/**
 * @return Point[]|Collection
 */
public function getPoints(): Collection;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question