The application method of PHP wrapper on SAE _php skill

Source: Internet
Author: User
Tags create directory memcached mkdir wrapper file permissions

This paper describes the application of PHP wrapper on SAE. Share to everyone for your reference, specific as follows:

One, PHP wrapper is what

since PHP 4.3, PHP has started to allow users to customize URL-style protocols via Stream_wrapper_register (). When a user uses a file system function, such as fopen (), copy (), to manipulate the encapsulation protocol, PHP invokes the corresponding function in the class provided by the registration protocol.
An example is given in the PHP manual, which registers the Variablestream class as a var://protocol through which users can read and write directly to global variables using file system functions. For example, a user can read and write $GLOBALS [' foo '] through "Var://foo".

Second, the SAE why the need for PHP wrapper

For performance and security reasons, local file reads and writes and external data fetching are disabled on the SAE platform. Accordingly, we provide the corresponding service to do the same thing.

Because the interface of the new service and the interface of PHP itself is not quite the same, the program specially developed for our platform is certainly not a problem, but a large number of existing programs and open source projects, is facing a complex migration work. Using PHP wrapper to encapsulate the interface of our services, users can easily migrate programs to the SAE platform.

Third, how to write PHP wrapper

To encapsulate a protocol through PHP wrapper, first, we need to write a Streamwrapper class, the class name can be customized, and the format of the class is:

Streamwrapper {public resource $context; __construct (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) resource stream_cast (int $cast _as) public void stream_close (void) public bool  tream_eof (void) public bool Stream_flush (void) public bool Stream_lock (mode $operation) public bool Stream_open ( String $path, String $mode, int $options, string & $opened _path) public string stream_read (int $count) Public b Ool Stream_seek (int $offset, int $whence = seek_set) public bool Stream_set_option (int $option, int $arg 1, int $ar G2) public array stream_stat (void) public int stream_tell (void) public int stream_write (string $data) public Boo L Unlink (String $pathPublic array Url_stat (string $path, int $flags)}

 

Description of each method in the class:

Streamwrapper::__construct-constructor, only called before Stream_open
Streamwrapper::d ir_closedir-Closes the directory handle and responds to the Closedir () function
Streamwrapper::d ir_opendir-Open the directory handle and respond to the opendir () function
Streamwrapper::d ir_readdir-reads an entry from a directory handle, responding to the Readdir () function
Streamwrapper::d ir_rewinddir-back to the directory handle, response to the Rewinddir () function
streamwrapper::mkdir-Create directory, respond to mkdir () function
streamwrapper::rename-directory or file Rename, response to rename () function
streamwrapper::rmdir-deletes the directory and responds to the rmdir () function
streamwrapper::stream_cast-retrieves the underlying resource and responds to the Stream_select () function
Streamwrapper::stream_close-closes the resource, responding to the fclose () function
streamwrapper::stream_eof-Check that the file pointer is already at the end of the file and respond to the feof () function
streamwrapper::stream_flush-clears the output cache, responding to the fflush () function
streamwrapper::stream_lock-Consulting file locking, responding to flock () function
streamwrapper::stream_open-open file or URL as stream, respond to fopen () function
Streamwrapper::stream_read-reads content from the stream, responds to Fread (), fgets () function
streamwrapper::stream_seek-position the pointer in the stream, responding to the fseek () function
streamwrapper::stream_set_option-Change flow settings
streamwrapper::stream_stat-retrieves information about a file resource and responds to the Fstat () function
streamwrapper::stream_tell-retrieves the position of the pointer in the stream, responding to the Ftell () function
Streamwrapper::stream_write-writes content to the stream, responds to Fwrite (), fputs () function
streamwrapper::unlink-Delete file, respond to unlink () function
streamwrapper::url_stat-retrieves information about the file, responding to all stat ()-related functions, such as file_exists (), Is_dir (), Is_file (), FileSize (), Fileinode (), etc.

For more information please refer to PHP Manual: http://cn2.php.net/manual/en/class.streamwrapper.php

After you have written the Streamwrapper class, use Stream_wrapper_register () to register the class with the wrapper and start using it. The function uses the following method:

BOOL Stream_wrapper_register (String $protocol, string $classname [, int $flags = 0])

For example:

Stream_wrapper_register ("Saemc", "Saememcachewrapper");

Because the SAE platform does not support write operations on local files, some open-source projects such as smarty that need to write files locally cannot be used directly on the SAE platform, and with SAEMC wrapper, users can save Smarty-compiled templates in the MC, It is convenient to move Smarty to SAE platform.

In the annex we provide you with the SAE on the Memcache wrapper implementation code, you can download this attachment for testing.

Before testing, you need to start a local memcached service with a port of 22222:

Memcached-m 10-p 22222-u nobody-l 127.0.0.1

You can then use the following code to test:

Contains the attachment code, registered SAEMC wrapper include_once (' wrapper.php ');
Test SAEMC Wrapper $fp = fopen ("Saemc://test.txt", "w+") or Die ("fopen faild!");
Fwrite ($fp, "line1\n") or Die ("fwrite line1 faild!");
Fwrite ($fp, "line2\n") or Die ("Fwrite line2 faild!");
Fwrite ($fp, "line3\n") or Die ("fwrite line3 faild!");
Var_dump (Ftell ($fp));
Fseek ($fp, 0);
      while (!feof ($fp)) {$c = fgets ($fp) or Die ("fgets faild!");
Var_dump ($c);
} fclose ($FP);
Var_dump (file_get_contents ("Saemc://test.txt"));
Var_dump (file_put_contents ("Saemc://path/test.txt", "Hello world!\n"));
Var_dump (file_put_contents ("Saemc://path/test.txt", "Hello world!\n", file_append));
Var_dump (file_get_contents ("Saemc://path/test.txt"));
Var_dump (Copy ("Saemc://path/test.txt", "Saemc://path/test_new.txt"));
Var_dump (file_get_contents ("Saemc://path/test_new.txt"));
Var_dump (Unlink ("Saemc://path/test.txt"));
Var_dump (file_get_contents ("Saemc://path/test.txt")); Var_dump (Rename ("Saemc://path/test_new.txt", "saemc://path/tesT.txt "));
Var_dump (file_get_contents ("Saemc://path/test.txt"));
echo "====test include====\n";

 Include_once ("Saemc://path/test.txt");

Test the output of the page:

Int (a)
string (6) "Line1
"
string (6) "Line2
"
string (6) "Line3" string (a
) line1
line2
line3 "int" (a)
string Hello world!
Hello world!
"
BOOL (TRUE)
string "Hello world!
Hello world!
"
BOOL (TRUE)
bool (FALSE)
bool (TRUE)
string (num) Hello world!
Hello world!
"
====test include====
Hello world!
Hello world!

We provide the Memcache wrapper does not implement the directory operation of some methods and Memcache timeout, you can refer to the PHP manual, try to implement directory operations, or through the context to enable this wrapper to support Memcache timeout.

In addition, you can go to the following address to see the sae_include in SAE Stdlib source, in which we are storage services encapsulated Saestor wrapper and Fetchurl services to be encapsulated the implementation of the HTTP wrapper:

http://stdlib.sinaapp.com/?f=sae_include.function.php

Iv. some points for attention when writing wrapper

1. Constructor function

The Streamwrapper class is very special, and its constructors are not called every time. It is only invoked when your operation triggers stream_open related actions, such as you use File_get_contents (). And when your operation triggers a stream-independent function, such as file_exists triggers the Url_stat method, the constructor is not invoked at this time.

2. Read implementation

Wrapper there are position and seek concepts, but a lot of services is actually a one-time read all the data, this can be a one-time read back in Stream_open, put into a property, In the future seek and tell when the direct operation of the property inside the data can be.

3. Append Write implementation

There are many services that write all of the data at once and do not support additional write functionality (such as memcache), which requires that we implement append writing in wrapper. You can read the entire value once, append the data that needs to be written to the read content, and write back again.

However, the performance of this type of append write is poor, especially when the content is large, a one-time read all the content will be very consuming resources, so in some services we have to discard the support of the append write.

4. Implementation of Url_stat

In the realization of Streamwrapper class, the realization of url_stat is a difficult problem. It is necessary to implement url_stat correctly so that the functions of querying file meta information such as is_writable and is_readable can work properly.

And we need to forge these values for our virtual devices. Take MC As an example, we give you some reference data:

Url_stat should return an array, divided into 13 entries, as follows:

Dev Equipment Number-write 0;
Ino inode number-write 0;
Mode file mode-This is the permission control symbol for the file, which is described later in detail;
Nlink Link-write 0;
The UID Uid-linux can be taken with posix_get_uid on Windows 0;
The GID Gid-linux can be taken with posix_get_gid on Windows 0;
Rdev Device Type-When the inode device has a value;
Size-File sizes;
Atime-The last read time format is a UNIX timestamp;
Mtime-Last write time;
CTime-creation time;
Blksize-blocksize of filesystem IO write 0;
Blocks-number of 512-byte blocks allocated write 0;

Where the value of mode must be written to:

If it is a file, its value is:

0100000 + file permissions, such as 0100000 + 0777.

If it is a directory, its value is:

040000 + directory permissions, such as 0400000 + 0777.

5. About STAT Caching

PHP caches the metadata of the file during the execution of the same page.
According to the PHP documentation for the Clearstatcache () the description of this method is known: In the use of stat (), Lstat (), file_exists (), is_writable (), is_readable (), is_executable (), Is_file (), Is_dir (), Is_link (), Filectime (), Fileatime (), Filemtime (), Fileinode (), filegroup (), Fileowner (), FileSize ( ), filetype (), or the Fileperms () method queries file information, PHP caches the file's stat to improve performance. The Clearstatcache () method can be used to clear the cache when unlink () automatically clears the stat cache.

In fact, PHP clears the stat cache only when the local files are unlink, rename and rmdir operations, and the wrapper cache is not cleared when unlink, rename, and RmDir are done through other stat operations. So in writing wrapper we have to clear stat cache by Clearstatcache () in unlink and other methods.

Click here to download the attachment.

More about PHP Interested readers can view the site topics: "Php Curl Usage Summary", "PHP Socket Usage Summary", "PHP Network Programming Skills Summary", "PHP basic Grammar Introductory Course", "PHP operation Office Document skills Summary (including Word, Excel,access,ppt), "The PHP date and time usage summary", "PHP object-oriented Programming Introduction Tutorial", "PHP string (String) Usage Summary", "Php+mysql Database operation Introduction Tutorial" and "PHP common database Operation skill Summary"

I hope this article will help you with the PHP program design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.