SG: A Simple PHP Grammar Sugar Extension

  php

Guide to exotic techniques
Grammatical sugar often provides programmers with a more practical coding method, which can make the code more concise and fluent and the semantics more natural. This article introduces the PHP syntax sugar extension written by the author himself, which extends a brand-new way of obtaining PHP super-global variables.
The author of this article is Fan Jiapeng, member of TC of 360 Technical Committee –WEB Server.

1. Talk about grammar sugar

First of all, the word “grammatical sugar” is by no means a derogatory term. It can bring convenience to our development work. It is a lightweight and convenient way of writing. It will neither adversely affect the use of the language itself nor bring performance losses.

Under normal circumstances, the use of grammar sugar can increase the readability of the program, reduce the complexity of the program, reduce the chance of errors in the coding, and is friendly to development engineers and can improve our development efficiency.

Excellent grammar sugar should be an infusion of soul thoughts and the application of simple writing. Here I use a picture to show:

2. What is SG?

SGSuperglobals refers to all variables available in the global scope.SGA brand-new PHP super-global variable acquisition method is extended.

These super-global variables are: _SERVER, _GET, _POST, _FILES, _COOKIE, _SESSION, _REQUEST, _ENV.

Of course, it can also be applied to custom variable scenarios.

It is very important that:It is very simple!

2.1 Project Background

The starting point of this idea is very simple. We should be able to guess what it does from the extended name.

On the premise of optimal performance:

  • The method for obtaining HTTP parameters can be simplified in an easy-to-understand way
  • The HTTP parameter values need to be uniformly filtered, converted and decrypted.
  • Before getting HTTP parameters, some Predefined Operation are required.
  • For all behaviors of HTTP parameters, the corresponding PHP Superglobal needs to be updated synchronously.
  • It is only used when declaring, rather than requesting the PHP Superglobals to be swept from the beginning.
  • In global syntax, extend the ability to get HTTP parameters

So,SGThe reason for this is to solve the above problems. It provides a sweeter syntax. Currently, v3.0.0 has been released.

2.2 Project Address

https://github.com/yulonghu/sg 

Welcome to submit Issues~

The currently supported PHP versions are shown in the following figure:

3. characteristics of SG

  • Simple, Fast and Lightweight
  • Zero copy access PHP super-global variables, using SG will update PHP super-global variables synchronously
  • It supports calling custom functions before taking values. By default, string variables will automatically call PHP trim
  • Solve the problem of undefined series when using PHP super global variables (undefined variable, undefined offset)
  • When static methods are used, decimal points are used instead of PHP array dimensions
  • When global declaration is adopted, the PHP array dimension is replaced by underscore.
  • Configurable global $variable search depth is supported, default first-level search

4. configuration items (php.ini)

Configuration item Permissions Type Default value explain
sg.enable PHP_INI_SYSTEM bool 0 0 off 1 on
sg.global_level PHP_INI_SYSTEM bool 1 1 only supports first-level search 0 unlimited search
sg.func_name PHP_INI_ALL char trim Default callPHP trimFunction, also supports custom functions

5、Hash Map

PHP super global variables SG key Global statement Function
$GLOBALS No No sg::all()
$_SERVER s global $s sg::get/set/has/del(‘s’)
$_GET g global $g sg::get/set/has/del(‘g’)
$_POST p global $p sg::get/set/has/del(‘p’)
$_FILES f global $f sg::get/set/has/del(‘f’)
$_COOKIE c global $c sg::get/set/has/del(‘c’)
$_SESSION n global $n sg::get/set/has/del(‘n’)
$_REQUEST r global $r sg::get/set/has/del(‘r’)
$_ENV e global $e sg::get/set/has/del(‘e’)

6. Flow chart

6.1 global declaration (PHP7)

6.2 Function Mode

7、API

7.1 global statement

global $g_key, $p_key, $c_key, $s_key, $f_key, $n_key, $e_key, $r_key

7.2 Static Methods

bool sg::set(string $key, mixed $value)
 mixed sg::get(string $key [, mixed $default_value = null])
 bool sg::has(string $key)
 bool sg::del(string $key [, mixed $... ])
 array sg::all(void)

8. Examples

8.1 examples of global declarations

8.1.1 sg.global_level = 1

<?  php
 
 $_GET['key'] = 'GET_test_key';
 
 function testGlobal()
 {
 global $g_key;
 
 var_dump($g_key);
 
 $g_key = 'NEW_GET_test_key';
 }
 
 testGlobal();
 
 var_dump(sg::get('g.key'));
 var_dump($GLOBALS['g_key']);
 var_dump($g_key);
 var_dump($_GET['key']);

The output of the above example is as follows:

string(12) "GET_test_key"
 string(16) "NEW_GET_test_key"
 string(16) "NEW_GET_test_key"
 string(16) "NEW_GET_test_key"
 string(16) "NEW_GET_test_key"

8.1.2 sg.global_level = 0

<?  php

$_GET['key']['key1']['key2'] = 'GET_test_key';

function testGlobal()
{
global $g_key_key1_key2;
}

testGlobal();

var_dump(sg::get('g.key.key1.key2'));
var_dump($GLOBALS['g_key_key1_key2']);
var_dump($g_key_key1_key2);
var_dump($_GET['key']['key1']['key2']);

The output of the above example is as follows:

string(12) "GET_test_key"
string(12) "GET_test_key"
string(12) "GET_test_key"
string(12) "GET_test_key"

8.1.3 sg.func_name

<?  php
 
 ini_set('sg.func_name', 'decryptTest');
 
 $_POST['key'] = 'IEEgQmFuYW5hIA==';
 
 function decryptTest($data)
 {
 return trim(base64_decode($data));
 }
 
 var_dump($p_key);

The output of the above example is as follows:

string(8) "A Banana"

8.2 Examples of Static Methods

8.2.1 get/set/has/del()

<?  php
 
 $key = 'test';
 $val = 'A Banana';
 
 echo "------------------start\n";
 var_dump(sg::get($key));
 var_dump(sg::get($key, 'def'));
 var_dump(sg::has($key));
 
 echo "------------------set\n";
 var_dump(sg::set($key, $val));
 
 echo "------------------get\n";
 var_dump(sg::get($key));
 var_dump(sg::get($key, 'def'));
 var_dump(sg::has($key));
 
 echo "------------------del\n";
 var_dump(sg::del($key));
 
 echo "------------------get\n";
 var_dump(sg::get($key));
 var_dump(sg::has($key));

The output of the above example is as follows:

------------------start
 NULL
 string(3) "def"
 bool(false)
 ------------------set
 bool(true)
 ------------------get
 string(8) "A banana"
 string(8) "A banana"
 bool(true)
 ------------------del
 bool(true)
 ------------------get
 NULL
 bool(false)

8.2.2 sg.func_name

<?  php

ini_set('sg.func_name', 'encryptTest');

function decryptTest($data)
{
return trim(base64_decode($data));
}

function encryptTest($data)
{
return base64_encode(trim($data));
}

sg::set('user', encryptTest(' A Banana '));
var_dump(sg::get('user'));

The output of the above example is as follows:

string(8) "A Banana"

9. Performance Test

After a long time of scratching, how about the performance? I did a simple ab test (ab -c100 -n10000) in the local environment. The PHP test code is as follows:

9.1 default-source code

<?  php
/*  default.php */
for($i = 0;   $i < 1000;  $i++) {
if(isset($_GET['key'])) {
var_dump(trim($_GET['key']));
}
}

9.2 global Statement-Source Code

<?  php
/*  sg.php */
for($i = 0;   $i < 1000;  $i++) {
global $g_key;
var_dump($g_key);
}

Ab test results are as follows:

9.3 default-results

$ ab -c100 -n10000 localhost/default.php?  key=hello_world
Concurrency Level:      100
 Time taken for tests:   1.615 seconds
 Complete requests:      10000
 Failed requests:        0
 Write errors:           0
 Total transferred:      251370000 bytes
 HTML transferred:       250000000 bytes
 Requests per second:    6190.21 [#/sec] (mean)
 Time per request:       16.155 [ms] (mean)
 Time per request:       0.162 [ms] (mean, across all concurrent requests)
 Transfer rate:          151956.36 [Kbytes/sec] received

9.4 global Statement-Results

$ ab -c100 -n10000 localhost/sg.php?  key=hello_world
Concurrency Level:      100
 Time taken for tests:   1.441 seconds
 Complete requests:      10000
 Failed requests:        0
 Write errors:           0
 Total transferred:      251931544 bytes
 HTML transferred:       250557708 bytes
 Requests per second:    6938.67 [#/sec] (mean)
 Time per request:       14.412 [ms] (mean)
 Time per request:       0.144 [ms] (mean, across all concurrent requests)
 Transfer rate:          170709.87 [Kbytes/sec] received

10. General conclusion

SGHas the following advantages:

  • Compatible with the current mainstream PHP version
  • It provides a sweeter grammar and enriches the application of Superglobals.
  • We always believe that simplicity is king.

Note: global declaration only supports immutable variable names.

(360 technical original content, reprint please be sure to keep the two-dimensional code at the end of the article, thank you ~)

About 360 Technology

360 technology is a technology sharing public number created by 360 technology team, pushing technology dry goods every day.

For more technical information, please pay attention to “360 technology” WeChat public number