M
M
magary42016-10-07 23:19:15
symfony
magary4, 2016-10-07 23:19:15

How to "kill" a collection?

the service returns an array of objects of the User[] type , then
I need to transfer this data to 3 different places
in one place, I can transfer this array without changes
to others - you need to slightly modify
the type to transfer an array, each element of which will not be User but UserReduced,
tell me the solution or pattern

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis, 2016-10-08
@magary4

<?php

class User {}
class UserReduced {
    public function __construct(User $user) {
        $this->user = $user;
    }
}
class CustomUserCollection extends ArrayObject {
    public function __construct($input = [], $flags = 0, $iteratorClass = 'ArrayIterator') {
        // magic
        $input = array_map(function ($user) {
            return new UserReduced($user);
        }, $input);

        parent::__construct($input, $flags, $iteratorClass);
    }
}

$users = [];
for ($i = 0; $i < 10; ++$i) {
    $users[] = new User();
}

// Case
$userReduces = iterator_to_array(new CustomUserCollection($users));

R
romy4, 2016-10-07
@romy4

Is there any problem to make 3 copies of the array and then redux them?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question