简体   繁体   中英

stream context for custom stream wrappers

In the code snippet that follows this paragraph I'm creating a stream wrapper called test using the Test_Stream object. I'm trying to use stream context's with it and have a few questions. First here's the code:

<?php
class Test_Stream {
    public $context;

    public function __construct()
    {
        print_r(stream_context_get_options($this->context));
        exit;
    }
}

$context = array(
    'test' => array('key' => 'value'),
    'otherwrapper' => array('key' =>'value')
);
$context = stream_context_create($context);

stream_wrapper_register('test', 'Test_Stream');

$fp = fopen('test://www.domain.tld/whatever', 'r', false, $context);

So right now, in that code snippet, Test_Stream is being registered to the 'test' stream wrapper but... what if I didn't know in advance what the wrapper name would be or what if I wanted to leave it up to the developer to decide. How would you know what the wrapper name was in the class? Seems like you'd have to know it in advance to get the appropriate context options (unless you just assume that the first context option array is the correct one) but what if you weren't going to know it in advance?

You know on open which protocol is called, so, use your context there:

<?php
class Test_Stream {
    public $context;

    public function stream_open($path, $mode, $options, &$opened_path ){
        var_dump(parse_url($path, PHP_URL_SCHEME));
        exit;
    }
}

$context = array(
    'test' => array('key' => 'value'),
    'otherwrapper' => array('key' =>'value')
);
$context = stream_context_create($context);
stream_wrapper_register('test', 'Test_Stream');
$fp = fopen('test://www.domain.tld/whatever', 'r', false, $context);


string(4) "test"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM