라라벨을 사용하다보면, 가끔씩 같은 클래스명과 비슷한 역할을 가지지만, 다른 네임스페이스를 가지는 클래스들이 존재한다.
대표적인 사례로는 바로 라라벨에서 가장 많이 사용하는 데이터 래퍼(wrapper) 클래스,Collection이다.
Collection을 사용하기위해, PhpStorm을 두드리다보면, 어김없이 두녀석들이 힌팅이 된다.
바로, Illuminate\Support\Collection, Illuminate\Database\Eloquent\Collection 이다.
막연히, Eloquent를 사용하다가 모델을 담는 Collection이 만들어지면, 후자를 사용하고, 평소에 데이터를 다루기 위해서는 전자를 사용한다고 생각하고 사용해왔는데, 뭐가 뭔지 정확히 판별해가면서 사용한적은 없는 것 같다.
오늘 이런 궁금증을 좀 해결해보려고 한다.
조사 순서는 정의 - 비교 - 사용 사례 순이다.
1. Illuminate\Support\Collection이 뭔데?
조사에 앞서, 네임 스페이스를 일일히 붙여서 부르기 귀찮으니, 서포트 컬렉션과, 엘로퀀트 컬렉션으로 나눠 부르도록 하자.
먼저, 서포트 컬렉션에 대한 정의이다.
https://laravel.com/docs/10.x/collections
Laravel - The PHP Framework For Web Artisans
Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.
laravel.com
공식 문서에서의 설명
The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data. For example, check out the following code. We'll use the collect helper to create a new collection instance from the array, run the strtoupper function on each element, and then remove all empty elements:
쉽게 말해서, 라라벨에서 배열을 다루기 위한, wrapper 클래스라고 볼 수 있다.
아래와 같이 collect 헬퍼를 이용하여 생성할 수 있다.
$collection = collect([1, 2, 3]);
특성은 아래와 같다.
1. macroable
Collection 자체에 매크로를 설정하여, Collection을 확장할 수 있다.
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Lang;
Collection::macro('toLocale', function (string $locale) {
return $this->map(function (string $value) use ($locale) {
return Lang::get($value, [], $locale);
});
});
$collection = collect(['first', 'second']);
$translated = $collection->toLocale('es');
2. 여러 메소드
wrapper class 이기 때문에, 데이터와 관련해서 여러 유용한 메소드들이 존재한다.
예를 들면, avg
, chunk, collapse, combine 등등이 있다.그중에서 특히, 내가 자주 사용하는 메소드는
where
https://laravel.com/docs/10.x/collections#method-where
isEmpty
https://laravel.com/docs/10.x/collections#method-isempty
Laravel - The PHP Framework For Web Artisans
Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.
laravel.com
등등이 있다.
3. Lazy Collections
지연 컬렉션은 메모리 사용량을 적게 유지하면서도 매우 큰 데이터 셋을 처리할 수 있게 해주는 기능으로 다음에 더 자세히 다룰 기회가 있을때, 찾아보도록 하겠다.
2. Illuminate\Database\Eloquent\Collection은 뭔데?
https://laravel.com/docs/10.x/eloquent-collections
Laravel - The PHP Framework For Web Artisans
Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.
laravel.com
엘로퀀트는 laravel에서 사용하는 ORM (eloquent에 대해서도 추후 다뤄보겠다.) 으로 모델과 관련하여 쿼리를 사용하거나 다루는 등 다양한 작업을 수행할 수 있게 해주는 모듈이다. 이러한 모듈에서 정의하고 있는 엘로퀀트 컬렉션은 서포트 컬렉션이라는 기본적인 laravel 데이터 wrapper 클래스를 상속받아 엘로퀀트에서 제공하는 기능들을 추가적으로 사용할 수 있게 해주는 컬렉션 클래스이다.
특성은 아래와 같다.
추가적인 메소드
등등..
대부분 엘로퀀트의 eager loading이나, 쿼리 작업과 관련하여 도움을 주는 메서드들이다.
모델에서 다루는 컬렉션 확장
Custom Collections
라는 이름으로 사용할 수 있는 이 기능은 특정 모델에서 newCollection 메서드를 통해 eloquent 컬렉션을 상속 받은 새로운 컬렉션을 해당 모델을 다룰 때 사용할 수 있게 해주는 기능이다.
둘 간의 비교
결국 정리해보면, 엘로퀀트 컬렉션이 서포트 컬렉션을 상속하여, 더 세부적인 기능을 사용할 수 있게 해주는 클래스이므로, 엘로퀀트와 관련된 작업을 수행할때에는 엘로퀀트 컬렉션을, 범용적으로 기능을 다루기 위해서는 서포트 컬렉션을 사용하면 되는 것이다.
'개발 > 라라벨' 카테고리의 다른 글
eloquent 모델에 keyType 지정하지 않을 시, relation에 접근할 수 없는 이슈 (1) | 2023.10.17 |
---|---|
tap, tap, tap (0) | 2023.09.27 |
laravel Request life-cycle (생명주기) dd로 따라가보기 (2) (0) | 2023.09.11 |
laravel Request life-cycle (생명주기) dd로 따라가보기 (1) (0) | 2023.09.05 |
laravel Notification queue 적용시에 모델에 따라서 memory size exhausted 되는 이슈 해결기 (0) | 2023.08.29 |