M
M
Max Ba2019-08-05 14:34:43
PHP
Max Ba, 2019-08-05 14:34:43

How to combine output methods and sort methods?

Need it

foreach($product_collection->getAll() as $v){
  //...
}

replaced by
foreach($product_collection->getAll()->sortByName() as $v){
  //...
}

I can't figure out how to implement such a construction inside an object.
The getAll() method returns all objects, and sorting by design should be applied to the resulting objects.
Only came to mind
$product_collection->getData()->sortByName()->getAllObj();
//или
$product_collection->sortByName()->getAll();

How about in my example?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kafkiansky, 2019-08-05
@mad_maximus

To call methods in a chain, you need to return $this from the method if the method is inside this class, or return some object (for example, return new SortClass()).

public function getAll()
{
   // code
   return new ArrayCollection($posts);
}

...

class ArrayCollection
{
    private $collection;
    
    public function __construct($collection)
    {
         $this->collection = $collection;
    }
   
    public function sortByName()
    {
        return array_filter($this->collection, function(){});
    }
}

Something like this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question