Streams
Streams
PHP에서 파일을 읽고, 네트워크로 통신하고, 데이터를 압축하는 작업은 겉보기엔 서로 달라 보이지만 사실 공통점이 있어요. 모두 같은 방식으로 읽고 쓸 수 있으면 좋겠죠. Stream(스트림)은 이런 파일·네트워크·압축 등 여러 작업을 하나의 공통된 방식으로 추상화하는 개념이에요.
출처: Streams
본문
Stream(스트림)은 파일, 네트워크, 데이터 압축 그 외에 공통된 함수 묶음과 용법을 공유하는 작업들을 일반화하는 방식이에요. 가장 단순하게 정의하면, 스트림은 스트림 가능(streamable)한 동작을 보이는 리소스(resource) 객체예요. 즉 선형적으로 읽거나 쓸 수 있고, fseek()로 스트림 안의 임의 위치로 이동할 수도 있어요.
**래퍼(wrapper)**는 스트림이 특정 프로토콜·인코딩을 어떻게 다룰지 알려주는 추가 코드예요. 예를 들어 http 래퍼는 URL을 원격 서버의 파일을 위한 HTTP/1.0 요청으로 바꾸는 방법을 알아요. PHP에는 기본 내장된 래퍼가 많고(Supported Protocols and Wrappers 참고), PHP 스크립트 안에서 stream_wrapper_register()로 또는 확장에서 직접 커스텀 래퍼를 추가할 수 있어요.
어떤 종류의 래퍼든 PHP에 추가할 수 있기 때문에, 래퍼로 처리할 수 있는 것에는 정해진 한계가 없어요. 현재 등록된 래퍼 목록은 stream_get_wrappers()로 확인할 수 있어요.
스트림은 scheme://target 형태로 참조해요.
scheme(string) — 사용할 래퍼의 이름이에요. 예로file,http,https,ftp,ftps,compress.zlib,compress.bz2,php가 있어요. PHP 내장 래퍼 목록은 Supported Protocols and Wrappers를 참고해요. 래퍼를 지정하지 않으면 함수 기본값(보통file://)이 사용돼요.target— 사용하는 래퍼에 따라 달라져요. 파일시스템 관련 스트림이면 보통 원하는 파일의 경로와 파일명이 되고, 네트워크 관련 스트림이면 보통 호스트명(때로는 경로가 붙음)이 돼요. 내장 스트림의 target 설명도 Supported Protocols and Wrappers에서 확인할 수 있어요.
설치·설정(Installing/Configuring)
- 스트림 클래스(Stream Classes)
- 사전 정의 상수(Predefined Constants)
- 스트림 필터(Stream Filters)
- 스트림 컨텍스트(Stream Contexts)
- 스트림 오류(Stream Errors)
- 예제(Examples) — 스트림 래퍼로 등록된 예제 클래스(Example class registered as stream wrapper)
php_user_filter 클래스
php_user_filter— php_user_filter 클래스php_user_filter::filter— 필터 적용 시 호출돼요(Called when applying the filter).php_user_filter::onClose— 필터를 닫을 때 호출돼요(Called when closing the filter).php_user_filter::onCreate— 필터를 만들 때 호출돼요(Called when creating the filter).
streamWrapper 클래스
streamWrapper— streamWrapper 클래스streamWrapper::__construct— 새 스트림 래퍼를 생성해요(Constructs a new stream wrapper).streamWrapper::__destruct— 기존 스트림 래퍼를 소멸해요(Destructs an existing stream wrapper).streamWrapper::dir_closedir— 디렉터리 핸들을 닫아요(Close directory handle).streamWrapper::dir_opendir— 디렉터리 핸들을 열어요(Open directory handle).streamWrapper::dir_readdir— 디렉터리 핸들에서 항목을 읽어요(Read entry from directory handle).streamWrapper::dir_rewinddir— 디렉터리 핸들을 되감아요(Rewind directory handle).streamWrapper::mkdir— 디렉터리를 만들어요(Create a directory).streamWrapper::rename— 파일이나 디렉터리의 이름을 바꿔요(Renames a file or directory).streamWrapper::rmdir— 디렉터리를 제거해요(Removes a directory).streamWrapper::stream_cast— 내부 리소스를 가져와요(Retrieve the underlying resource).streamWrapper::stream_close— 리소스를 닫아요(Close a resource).streamWrapper::stream_eof— 파일 포인터에서 파일 끝을 검사해요(Tests for end-of-file on a file pointer).streamWrapper::stream_flush— 출력을 비워요(Flushes the output).streamWrapper::stream_lock— 권고적 파일 잠금(Advisory file locking).streamWrapper::stream_metadata— 스트림 메타데이터를 변경해요(Change stream metadata).streamWrapper::stream_open— 파일이나 URL을 열어요(Opens file or URL).streamWrapper::stream_read— 스트림에서 읽어요(Read from stream).streamWrapper::stream_seek— 스트림의 특정 위치로 이동해요(Seeks to specific location in a stream).streamWrapper::stream_set_option— 스트림 옵션을 변경해요(Change stream options).streamWrapper::stream_stat— 파일 리소스에 대한 정보를 가져와요(Retrieve information about a file resource).streamWrapper::stream_tell— 스트림의 현재 위치를 가져와요(Retrieve the current position of a stream).streamWrapper::stream_truncate— 스트림을 자릿수에 맞춰 잘라요(Truncate stream).streamWrapper::stream_write— 스트림에 써요(Write to stream).streamWrapper::unlink— 파일을 삭제해요(Delete a file).streamWrapper::url_stat— 파일에 대한 정보를 가져와요(Retrieve information about a file).
StreamBucket 클래스
StreamBucket— StreamBucket 클래스
Stream 함수(Stream Functions)
stream_bucket_append— brigade에 bucket을 추가해요(Append bucket to brigade).stream_bucket_make_writeable— 조작할 brigade에서 bucket 객체를 반환해요(Returns a bucket object from the brigade to operate on).stream_bucket_new— 현재 스트림에서 쓸 새 bucket을 만들어요(Create a new bucket for use on the current stream).stream_bucket_prepend— brigade 앞에 bucket을 추가해요(Prepend bucket to brigade).stream_context_create— 스트림 컨텍스트를 만들어요(Creates a stream context).stream_context_get_default— 기본 스트림 컨텍스트를 가져와요(Retrieve the default stream context).stream_context_get_options— 스트림/래퍼/컨텍스트의 옵션을 가져와요(Retrieve options for a stream/wrapper/context).stream_context_get_params— 컨텍스트에서 매개변수를 가져와요(Retrieves parameters from a context).stream_context_set_default— 기본 스트림 컨텍스트를 설정해요(Set the default stream context).stream_context_set_option— 스트림/래퍼/컨텍스트의 옵션을 설정해요(Sets an option for a stream/wrapper/context).stream_context_set_options— 지정한 컨텍스트에 옵션을 설정해요(Sets options on the specified context).stream_context_set_params— 스트림/래퍼/컨텍스트의 매개변수를 설정해요(Set parameters for a stream/wrapper/context).stream_copy_to_stream— 한 스트림에서 다른 스트림으로 데이터를 복사해요(Copies data from one stream to another).stream_filter_append— 스트림에 필터를 추가해요(Attach a filter to a stream).stream_filter_prepend— 스트림에 필터를 앞에 추가해요(Attach a filter to a stream).stream_filter_register— 사용자 정의 스트림 필터를 등록해요(Register a user defined stream filter).stream_filter_remove— 스트림에서 필터를 제거해요(Remove a filter from a stream).stream_get_contents— 스트림의 나머지를 문자열로 읽어요(Reads remainder of a stream into a string).stream_get_filters— 등록된 필터 목록을 가져와요(Retrieve list of registered filters).stream_get_line— 주어진 구분자까지 스트림 리소스에서 줄을 가져와요(Gets line from stream resource up to a given delimiter).stream_get_meta_data— 스트림/파일 포인터에서 헤더/메타 데이터를 가져와요(Retrieves header/meta data from streams/file pointers).stream_get_transports— 등록된 소켓 전송 목록을 가져와요(Retrieve list of registered socket transports).stream_get_wrappers— 등록된 스트림 목록을 가져와요(Retrieve list of registered streams).stream_is_local— 스트림이 로컬 스트림인지 검사해요(Checks if a stream is a local stream).stream_isatty— 스트림이 TTY인지 검사해요(Check if a stream is a TTY).stream_notification_callback— 알림 컨텍스트 매개변수의 콜백 함수(A callback function for the notification context parameter).stream_register_wrapper—stream_wrapper_register의 별칭(Alias of stream_wrapper_register).stream_resolve_include_path— include 경로에 대해 파일명을 해석해요(Resolve filename against the include path).stream_select— 초와 마이크로초로 지정된 타임아웃과 함께 주어진 스트림 배열에 대해select()시스템 호출에 해당하는 동작을 수행해요(Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds).stream_set_blocking— 스트림에 블로킹/논블로킹 모드를 설정해요(Set blocking/non-blocking mode on a stream).stream_set_chunk_size— 스트림 청크 크기를 설정해요(Set the stream chunk size).stream_set_read_buffer— 주어진 스트림에 읽기 파일 버퍼링을 설정해요(Set read file buffering on the given stream).stream_set_timeout— 스트림에 타임아웃 기간을 설정해요(Set timeout period on a stream).stream_set_write_buffer— 주어진 스트림에 쓰기 파일 버퍼링을 설정해요(Sets write file buffering on the given stream).stream_socket_accept—stream_socket_server로 만든 소켓에서 연결을 수락해요(Accept a connection on a socket created by stream_socket_server).stream_socket_client— 인터넷 또는 Unix 도메인 소켓 연결을 열어요(Open Internet or Unix domain socket connection).stream_socket_enable_crypto— 이미 연결된 소켓의 암호화를 켜거나 꺼요(Turns encryption on/off on an already connected socket).stream_socket_get_name— 로컬 또는 원격 소켓의 이름을 가져와요(Retrieve the name of the local or remote sockets).stream_socket_pair— 구분할 수 없는 연결된 소켓 스트림 쌍을 만들어요(Creates a pair of connected, indistinguishable socket streams).stream_socket_recvfrom— 연결 여부와 관계없이 소켓에서 데이터를 받아요(Receives data from a socket, connected or not).stream_socket_sendto— 연결 여부와 관계없이 소켓에 메시지를 보내요(Sends a message to a socket, whether it is connected or not).stream_socket_server— 인터넷 또는 Unix 도메인 서버 소켓을 만들어요(Create an Internet or Unix domain server socket).stream_socket_shutdown— 전이중 연결을 종료해요(Shutdown a full-duplex connection).stream_supports_lock— 스트림이 잠금을 지원하는지 알려줘요(Tells whether the stream supports locking).stream_wrapper_register— PHP 클래스로 구현된 URL 래퍼를 등록해요(Register a URL wrapper implemented as a PHP class).stream_wrapper_restore— 이전에 등록 해제한 내장 래퍼를 복원해요(Restores a previously unregistered built-in wrapper).stream_wrapper_unregister— URL 래퍼의 등록을 해제해요(Unregister a URL wrapper).
더 알아보기
- 스트림 개념과 래퍼·컨텍스트·필터의 관계는 PHP에서 파일·네트워크 I/O를 다룰 때 바탕이 돼요.
file_get_contents(),fopen()이 사실 내부적으로 파일 래퍼(file://)를 거친다는 점을 알면 스트림 추상화가 체감돼요.