In Java, stream is a very important concept.
The concept of stream originates from the concept of pipe in UNIX. In UNIX, a pipe is an uninterrupted byte stream, used to implement communication between programs or processes, or to read and write peripheral devices, external files, etc. According to the direction of the stream, it can be divided into input stream and output stream. At the same time, other streams can be placed around it, such as buffer stream, so that more stream processing methods can be obtained.
Streams in PHP and streams in Java are actually the same concept, just a little simpler. Since PHP is mainly used for web development, the concept of "flow" is rarely mentioned. If you have a Java foundation, it will be easier to understand streams in PHP. In fact, many advanced features in PHP, such as SPL, exceptions, filters, etc., all refer to the implementation of Java and have the same concepts and principles.
For example, the following is a usage of the PHP SPL standard library (traverse the directory and find files with fixed conditions):
/**
* Provide $path and generate the corresponding directory iterator
*/
public function __construct($path)
{
parent::__construct(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)));
}
/**
* Check whether the file extension meets the conditions
*/
public function accept()
{
$item = $this->getInnerIterator();
if ($item->isFile( ) && in_array(pathinfo($item->getFilename(), PATHINFO_EXTENSION), $this->ext))
>
// Instantiate
foreach (new RecursiveFileFilterIterator('D:/history') as $item)
{
echo $item . PHP_EOL;
There is also the same code in Java:
Copy code
The code is as follows:
FilenameFilter textFilter = new FilenameFilter()
{
public boolean accept(File dir, String name)
{
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(".txt"))
{
return true;
}
else
{
return false;
}
}
};
File[] files = f.listFiles(textFilter);
for (File file : files)
{
if (file.isDirectory())
{
System.out.print("directory:");
}
else
{
System.out.print(" file:");
}
System.out.println(file.getCanonicalPath());
}
}
}
举这个例子,一方面是说明PHP和Java在很多方面的概念是一样的,掌握一种语言对理解另外一门语言会有很大的帮助;另一方面,这个例子也有助于我们下面要提到的过滤器流-filter。其实也是一种设计模式的体现。
我们可以通过几个例子先来了解stream系列函数的使用。
下面是一个使用socket来抓取数据的例子:
$data=http_build_query($post_);
$fp = fsockopen("nowamagic.net", 80, $errno, $errstr, 5);
$out="POST http://nowamagic.net/news/1/comment HTTP/1.1rn";
$out.="Host: typecho.orgrn";
$out.="User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13"."rn";
$out.="Content-type: application/x-www-form-urlencodedrn";
$out.="PHPSESSID=082b0cc33cc7e6df1f87502c456c3eb0rn";
$out.="Content-Length: " . strlen($data) . "rn";
$out.="Connection: closernrn";
$out.=$data."rnrn";
fwrite($fp, $out);
while (!feof($fp))
{
echo fgets($fp, 1280);
}
fclose($fp);
我们也可以用stream_socket 实现,这很简单,只需要打开socket的代码换成下面的即可:
Let’s look at another example of stream:
The file_get_contents function is generally used to read file contents, but this function can also be used to grab remote URLs, playing a similar role to curl.
$context = stream_context_create($opts);
file_get_contents('http://www.jb51.net/news', false, $context);
Note that the third parameter, $context, is the HTTP stream context, which can be understood as a pipe attached to the file_get_contents function. In the same way, we can also create FTP streams and socket streams and set them in the corresponding functions.
For more information about stream_context_create, please refer to: PHP function completion: stream_context_create() simulates POST/GET.
The two stream series functions mentioned above are wrapper-like streams that act on the input and output streams of a certain protocol. This kind of usage and concept is actually not much different from streams in Java. For example, Java often writes like this:
One layer of flow is nested within another layer of flow, which is similar to that in PHP.
Let’s look at the function of the filter stream:
/* Apply the rot13 filter to the write stream */
stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE);
/* The written data is processed by the rot13 filter*/
fwrite($fp, "This is a testn");
rewind($fp);
/* Read and write data, the uniqueness is naturally the processed characters */
fpassthru($fp);
fclose($fp);
// output: Guvf vf n grfg
In the above example, if we set the filter type to STREAM_FILTER_ALL, which acts on the read and write streams at the same time, then the read and write data will be processed by the rot13 filter, and the data we read will be the same as the data we wrote. The original data entered is consistent.
You may be surprised that the variable "string.rot13" in stream_filter_append comes from nowhere. This is actually a filter built into PHP.
Use the following method to print out the PHP built-in stream:
Output:
Naturally, we will think of defining our own filters, which is not difficult:
use with use using use using ’ ’ ’ s ’ through ’ s ’ through ’s ’ through ‐ to ‐ ‐‐‐ return PSFS_PASS_ON;
}
}
stream_filter_register("string.md5", "md5_filter");
After that, you can use our custom filter "string.md5".
The way this filter is written seems a bit confusing. In fact, we only need to look at the structure and built-in methods of the php_user_filter class to understand.
The most suitable thing for the filter stream is file format conversion, including compression, encoding and decoding, etc. In addition to these "deviant" usages, one of the more useful aspects of the filter stream is debugging and logging functions, such as in socket During development, register a filter stream for log recording. For example, the following example:
$callback = function($data)
{
file_put_contents("c:log.txt",date("Y-m-d H:i")."rn");
This filter can not only process the input stream, but also callback a function for logging.
www.bkjia.com