PHP stream Streams, wrapper concept and usage examples, streamswrapper
This article describes the concepts and usage of PHP stream Streams and wrapper. We will share this with you for your reference. The details are as follows:
The concept of stream Streams was introduced in php4.3 and is an abstraction of stream data for unified data operations, such as file data, network data, and compressed data, so that the same function can be shared, the file system functions of php are shared like this. For example, the file_get_contents () function can open local files and access URLs. Simply put, a stream is a resource object that shows streaming data behavior.
Read and Write in a linear manner, and search can be performed anywhere in the stream.
The stream is similar to the database abstraction layer. In the database abstraction layer, no matter which database is used, data is operated in the same way on the abstraction layer, while the stream is the abstraction of data, whether it is a local file, a remote file, or a compressed file, as long as the stream data is used, the operation method is the same.
With the concept of stream, the wrapper concept is derived. Each stream corresponds to a package. A stream is a concept generated from the perspective of unified operations, the package is a concept generated from understanding the stream data content, that is, how to operate or configure different content in this unified operation mode;
These contents are all presented as streams, but the content rules are different. For example, the data transmitted from http is a stream, however, only the http Wrapper can understand the meaning of the data sent from the http protocol. In this way, a stream is a pipe, but it flows out data, the wrapper is an interpreter embedded in the outer layer of the pipe. It understands the meaning of the outgoing data and can operate on it.
The official manual said: "A package tells the stream How to handle additional code for special protocols or codes." Do you understand this sentence?
The package can be nested. After a package is wrapped out of a stream, the package can still be wrapped in the outer layer. At this time, the package in the layer acts as a stream as opposed to the package in the outer layer.
The C language development documentation implemented at the underlying layer of php provides the following explanations:
Stream API operations: at the basic level, Apis define php_stream objects to represent stream data sources. at a slightly higher level, Apis define php_stream_wrapper objects.
It wraps the lower-level php_stream object to provide the ability to retrieve URL content and metadata, add context parameters, and adjust the behavior of the package;
After each stream is opened, any number of filters can be applied to it, and the stream data will be processed by the filter. I think the word "filter" is a little inaccurate and misleading.
The literal sense is like removing some data. It should be called a data regulator, because it can remove or add or modify some data, but the historical reasons are generally the same, it is also called a filter, and everyone understands it.
We often see the following words to explain their differences:
Resources and data: resources are macro statements, usually containing data, while data is representative statements. During program development, data is often said to be data, while in software planning, resources are said to be resources, they are synonyms, just like the differences between software design and program development.
Context and parameter: context is a macro Statement, which is often used in communication. Specifically, it is a parameter of communication. The parameter statement is often used in specific tasks, such as functions.
The concepts are explained above. Let's take a look at the specific content below:
For the protocols and wrapper supported by php, see here:Http://php.net/manual/zh/wrappers.php:
(The author's note: the original title is: supported protocols and encapsulation protocols. Chinese translation is a bit misleading. To be precise, it is the supported protocols and wrapper. It is clear from the English version)
Some protocols and wrapper are supported by default. Use the stream_get_wrappers () function to view them. You can also customize a wrapper and register it with stream_wrapper_register ().
Although it can be used as a delimiter in RFC 3986, php only allows: //. Therefore, use the format "scheme: // target" for URLs.
File: //-access the local file system. This package is used by default when file system functions are used.
Http: //-access the HTTP (s) URL
Ftp: //-access FTP (s) URLs
Php: //-access each input/output stream (I/O streams)
Zlib: //-compressed stream
Data: //-data (RFC 2397)
Glob: //-find the matching file path Mode
Phar: //-PHP Archive
Ssh2: //-Secure Shell 2
Rar: //-RAR
Ogg: //-audio stream
CT: //-Process Interactive streams
How to implement a custom package:
When using file system functions such as fopen, fwrite, fread, fgets, feof, rewind, file_put_contents, file_get_contents, and so on, data is first transmitted to the defined package class object, the package then operates the stream.
How to implement a custom stream package? Php provides a class prototype, which is just a prototype. It is neither an interface nor a class and cannot be used for inheritance:
StreamWrapper {/* attribute */public resource $ context;/* Method */_ construct (void) _ destruct (void) public bool dir_closedir (void) public bool dir_opendir (string $ path, int $ options) public string dir_readdir (void) public bool dir_rewinddir (void) public bool mkdir (string $ path, int $ mode, int $ options) public bool rename (string $ path_from, string $ path_to) public bool rmdir (string $ path, int $ options) public resource stream_cast (int $ cast_as) public void stream_close (void) public bool stream_eof (void) public bool stream_flush (void) public bool stream_lock (int $ operation) public bool stream_metadata (string $ path, int $ option, mixed $ value) public bool stream_open (string $ path, string $ mode, int $ options, string & $ opened_path) public string stream_read (int $ count) public bool stream_seek (int $ offset, int $ whence = SEEK_SET) public bool stream_set_option (int $ option, int $ arg1, int $ arg2) public array stream_stat (void) public int stream_tell (void) public bool stream_truncate (int $ new_size) public int stream_write (string $ data) public bool unlink (string $ path) public array url_stat (string $ path, int $ flags )}
The methods defined in this prototype are defined according to their own needs and do not require full implementation. This is why the interface cannot be defined, because some implementations do not need some methods at all,
This brings a lot of flexibility. For example, the package does not support the delete directory rmdir function, so it does not need to be implemented.streamWrapper::rmdir
Because it is not implemented, if you call rmdir on the package, an error will be thrown. to customize this error, you can also implement it and throw an error inside it.
StreamWrapper is not a predefined class either.class_exists("streamWrapper")
It is just a prototype that guides developers.
The official manual provides an example: http://php.net/manual/zh/stream.streamwrapper.example-1.php
This blog provides an example of extracting modified wrappers from the drupal8 system. For more information, see the source code analysis of drupal8.
Stream Functions, Official manual: http://php.net/manual/zh/ref.stream.php
Common functions are as follows:
Stream_bucket_append function: adds data to a queue.
Stream_bucket_make_writeable function: returns a data object from the Operation queue.
Stream_bucket_new function: Creates a new data for the current queue.
Stream_bucket_prepend function: Prepare data to the queue
Stream_context_create function: create a data stream Context
Stream_context_get_default function: obtains the default data stream context.
Stream_context_get_options function: gets the data stream settings.
Stream_context_set_option: Set the data stream, data packet, or context.
Stream_context_set_params function: sets parameters for data streams, data packets, or context.
Stream_copy_to_stream function: replicate data streams.
Stream_filter_append function: adds a filter to the data stream.
Stream_filter_prepend function: adds a filter to the data stream.
Stream_filter_register function: registers a data stream filter and runs it as a PHP class.
Stream_filter_remove function: removes a filter from a data stream.
Stream_get_contents function: Read the remaining data from the data stream to the string
Stream_get_filters function: returns the list of registered data stream filters.
Stream_get_line function: obtains rows from data stream resources based on the given delimiters.
Stream_get_meta_data function: obtains the header/metadata from the encapsulation protocol file pointer.
Stream_get_transports function: return the registered Socket transport list
Stream_get_wrappers function: returns the list of registered data streams.
Stream_register_wrapper function: registers a URL Encapsulation Protocol implemented using the PHP class.
Stream_select function: receives data stream arrays and waits for their status to change.
Stream_set_blocking function: sets a data stream to congested or non-congested.
Stream_set_timeout function: sets the time-out of data streams.
Stream_set_write_buffer function: sets a buffer for the data stream.
Stream_socket_accept function: accepts the Socket connection created by the function stream _ socket_server ().
Stream_socket_client function: opens the Socket connection of the network or UNIX host
Stream_socket_enable_crypto function: Enables or disables Data Encryption For a connected Socket.
Stream_socket_get_name function: Get the local or network Socket name
Stream_socket_pair function: creates two non-differentiated Socket data stream connections.
Stream_socket_recvfrom function: obtains data from a Socket, regardless of whether it is connected or not.
Stream_socket_sendto function: sends data to the Socket, regardless of whether it is connected or not.
Stream_socket_server function: Creates a network or UNIX Socket server.
Stream_wrapper_restore function: Restores a previously logged-out data packet.
Stream_wrapper_unregister function: deregister a URL package
The column of a Filter and Its Explanation:
Link to the official website:
User filter base class: http://php.net/manual/zh/class.php-user-filter.php
Filter registration: http://php.net/manual/zh/function.stream-filter-register.php
<? Php/* define a filter */class strtoupper_filter extends php_user_filter {function filter ($ in, $ out, & $ consumed, $ closing) {while ($ bucket = stream_bucket_make_writeable ($ in) {// retrieve a piece of data from the stream $ bucket-> data = strtoupper ($ bucket-> data ); $ consumed + = $ bucket-> datalen; stream_bucket_append ($ out, $ bucket); // send the modified data to the output location} return PSFS_PASS_ON ;}} /* register the filter to php */stream_filter_register ("strtoupper", "strtoupper _ Filter ") or die (" Failed to register filter "); $ fp = fopen (" foo-bar.txt "," w "); /* apply the filter to a stream */stream_filter_append ($ fp, "strtoupper"); fwrite ($ fp, "Line1 \ n"); fwrite ($ fp, "Word-2 \ n"); fwrite ($ fp, "Easy As 123 \ n"); fclose ($ fp ); // read and display the content to change all to uppercase readfile ("foo-bar.txt");?>