Архив рубрики: php

php 7.1.1

Скомпилировал на raspberry pi php 7.1.1
./configure --prefix=/opt/php-7.1.1 --with-config-file-path=/opt/php-7.1.1/etc --with-zlib-dir --with-freetype-dir --enable-mbstring --with-libxml-dir=/usr --enable-soap --enable-calendar --with-curl --with-mcrypt --with-zlib --with-gd --disable-rpath --enable-inline-optimization --with-bz2 --with-zlib --enable-sockets --enable-sysvsem --enable-sysvshm --enable-pcntl --enable-mbregex --enable-exif --enable-bcmath --with-mhash --enable-zip --with-pcre-regex --with-pdo-mysql --with-mysqli --with-mysql-sock=/var/run/mysqld/mysqld.sock --with-jpeg-dir=/usr --with-png-dir=/usr --enable-gd-native-ttf --with-openssl --with-fpm-user=www-data --with-fpm-group=www-data --with-libdir=/usr/lib/arm-linux-gnueabihf --enable-ftp --with-kerberos --with-gettext --with-xmlrpc --with-xsl --enable-opcache --enable-fpm
и попробовал deployer для деплоя. Очень легко деплоится, мне понадобилось пара минут чтобы с нуля залить приложение на сервер, правда приложение простое и не ясно как будут проходить нестандартные задания, но думаю проще чем в капистрано.

getAllKeys в memcache

Не все расширения могут позволить работать с со всеми возможностями memcached, а некоторые функции работают неоптимально, например, getAllKeys выполняет запрос
stats cachedump N 0 200 раз (!). Я же предлагаю уйти от метода тотального перебора и спросить у сервера в каких точно slab он хранит данные. Для этого существует запрос stats items , привожу пример функции для кастомных запросов

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function getDataFromMemcached($command) {
  $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  if ($socket === FALSE)
    throw new Exception(socket_strerror(socket_last_error()));
  if (socket_connect($socket, memcached_host, memcached_port) === FALSE)
    throw new Exception(socket_strerror(socket_last_error()));
  if (socket_write($socket, "$command\n") === FALSE)
    throw new Exception(socket_strerror(socket_last_error()));
  $answer = "";
  while ($out = socket_read($socket, 1024, PHP_BINARY_READ)) {
    $answer .= $out;
    if (strlen($out) < 1024)
      break;
  }
  socket_close($socket);
  return $answer;
}
function getDataFromMemcached($command) {
  $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  if ($socket === FALSE)
    throw new Exception(socket_strerror(socket_last_error()));
  if (socket_connect($socket, memcached_host, memcached_port) === FALSE)
    throw new Exception(socket_strerror(socket_last_error()));
  if (socket_write($socket, "$command\n") === FALSE)
    throw new Exception(socket_strerror(socket_last_error()));
  $answer = "";
  while ($out = socket_read($socket, 1024, PHP_BINARY_READ)) {
    $answer .= $out;
    if (strlen($out) < 1024)
      break;
  }
  socket_close($socket);
  return $answer;
}

Вот допустим есть такая функция которая шлет запросы на сервер, теперь следует спросить у сервера Теперь следует спросить у сервера stats items, он скажет что-то вроде

................
STAT items:16:expired_unfetched 0
STAT items:16:evicted_unfetched 0
STAT items:17:number 4
STAT items:17:age 492
................

и становится понятно какие stab заняты. Затем извлечь идентификаторы slabs (это циферки 16,17…) и сделать запрос stats cachedump {$slab} 0 который вернет что нам нужно

ITEM b0d35f99c68e54c47a0839f5b4f91a73 [718 b; 1384951681 s]

потом остается только сделать get КЛЮЧ для получения значения. Пример выложен на гитхаб

Расчет выражения

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
define('FORMULA', '1+(1+1)*(1+1)/1+1-1+(1+1*1)-(1-(2-3-(4-5)))+1');
 
echo 'RESULT=' . p(FORMULA);
 
function p($expr, $offset=0) {
  $operands = array();
  while ($offset < strlen($expr)) {
    if (count($operands) == 3) {
      $operands = proccess($operands);
    }
 
  if (isComplex($expr[$offset])) {
    ++$offset;// Отрезаю первую скобку выражения
    $complexVar = p($expr, &$offset);
    $operands[] = array((int)$complexVar, $expr[$offset]);
    if (strlen($expr) > $offset + 1 && ! isEnd($expr[$offset]))
      ++$offset;
    } elseif (isEnd($expr[$offset])) {
      // должно быть два элемента
      $left = array_shift($operands);
      $center = array_shift($operands);
      $result = eval("return {$left[0]} {$left[1]} {$center[0]};");
      ++$offset;// Переходим к следующему сиволу после закрывающей скобки
      break;
    } elseif (preg_match('/(d)+/', $expr, $matches, 0, $offset)) {
      if (count($matches) > 1) {
        $operationPos = $offset + strlen($matches[1]);// Позиция операции=текущее смещение + длина
        if (($operationPos >= strlen($expr)) || isEnd($expr[$operationPos])) {// Конец выражения или строки
          if (count($operands) == 2) {
            $operands[] = array($matches[1], (strlen($expr) < $operationPos) ? $expr[$operationPos] : '');
            $operands = proccess($operands);
            $result = eval("return {$operands[0][0]} {$operands[0][1]} {$operands[1][0]};");
            if ($operationPos + 1 < strlen($expr))
              $offset = $operationPos + 1;
            break;
    } else {
      $result = eval("return {$operands[0][0]} {$operands[0][1]} {$matches[1][0]};");
      if ($operationPos + 1 < strlen($expr))
        $offset = $operationPos + 1;
      break;
    }
    } else {
  $operands[] = array((int)$matches[1], substr($expr, $operationPos, 1));
  // Сейчас позиция операции указывает на закрывающую скобку, двигаемся дальше
  if (strlen($expr) > $operationPos + 1)
    $offset = $operationPos + 1;
  }
    } else
      throw new Exception('?');
    } else {
      throw new Exception('?');
    }
  }
 
  return $result;
}
 
/*
* Из трех операндов делает два
*/
function proccess($operands) {
  if (in_array($operands[0][1], array('+', '-')) &&   (in_array($operands[1][1], array('*', '/')))) {
    // Центральный с правым
    $right = array_pop($operands);
    $center = array_pop($operands);
    echo "processing CR {$center[0]} {$center[1]} {$right[0]};n";
    $result = eval("return {$center[0]} {$center[1]} {$right[0]};");
    array_push($operands, array($result, $right[1]));
  } else {
    $left = array_shift($operands);
    $center = array_shift($operands);
    $result = eval("return {$left[0]} {$left[1]} {$center[0]};");
    echo "processing LC {$left[0]} {$left[1]} {$center[0]}=$result;n";
    array_unshift($operands, array((int)$result, $center[1]));
  }
  return $operands;
}
 
function isComplex($symbol) {
  return ($symbol == '(') ? TRUE : FALSE;
}
 
function isEnd($symbol) {
  return ($symbol == ')') ? TRUE : FALSE;
}
define('FORMULA', '1+(1+1)*(1+1)/1+1-1+(1+1*1)-(1-(2-3-(4-5)))+1');

echo 'RESULT=' . p(FORMULA);

function p($expr, $offset=0) {
  $operands = array();
  while ($offset < strlen($expr)) {
    if (count($operands) == 3) {
      $operands = proccess($operands);
    }

  if (isComplex($expr[$offset])) {
    ++$offset;// Отрезаю первую скобку выражения
    $complexVar = p($expr, &$offset);
    $operands[] = array((int)$complexVar, $expr[$offset]);
    if (strlen($expr) > $offset + 1 && ! isEnd($expr[$offset]))
      ++$offset;
    } elseif (isEnd($expr[$offset])) {
      // должно быть два элемента
      $left = array_shift($operands);
      $center = array_shift($operands);
      $result = eval("return {$left[0]} {$left[1]} {$center[0]};");
      ++$offset;// Переходим к следующему сиволу после закрывающей скобки
      break;
    } elseif (preg_match('/(d)+/', $expr, $matches, 0, $offset)) {
      if (count($matches) > 1) {
        $operationPos = $offset + strlen($matches[1]);// Позиция операции=текущее смещение + длина
        if (($operationPos >= strlen($expr)) || isEnd($expr[$operationPos])) {// Конец выражения или строки
          if (count($operands) == 2) {
            $operands[] = array($matches[1], (strlen($expr) < $operationPos) ? $expr[$operationPos] : '');
            $operands = proccess($operands);
            $result = eval("return {$operands[0][0]} {$operands[0][1]} {$operands[1][0]};");
            if ($operationPos + 1 < strlen($expr))
              $offset = $operationPos + 1;
            break;
    } else {
      $result = eval("return {$operands[0][0]} {$operands[0][1]} {$matches[1][0]};");
      if ($operationPos + 1 < strlen($expr))
        $offset = $operationPos + 1;
      break;
    }
    } else {
  $operands[] = array((int)$matches[1], substr($expr, $operationPos, 1));
  // Сейчас позиция операции указывает на закрывающую скобку, двигаемся дальше
  if (strlen($expr) > $operationPos + 1)
    $offset = $operationPos + 1;
  }
    } else
      throw new Exception('?');
    } else {
      throw new Exception('?');
    }
  }

  return $result;
}

/*
* Из трех операндов делает два
*/
function proccess($operands) {
  if (in_array($operands[0][1], array('+', '-')) &&   (in_array($operands[1][1], array('*', '/')))) {
    // Центральный с правым
    $right = array_pop($operands);
    $center = array_pop($operands);
    echo "processing CR {$center[0]} {$center[1]} {$right[0]};n";
    $result = eval("return {$center[0]} {$center[1]} {$right[0]};");
    array_push($operands, array($result, $right[1]));
  } else {
    $left = array_shift($operands);
    $center = array_shift($operands);
    $result = eval("return {$left[0]} {$left[1]} {$center[0]};");
    echo "processing LC {$left[0]} {$left[1]} {$center[0]}=$result;n";
    array_unshift($operands, array((int)$result, $center[1]));
  }
  return $operands;
}

function isComplex($symbol) {
  return ($symbol == '(') ? TRUE : FALSE;
}

function isEnd($symbol) {
  return ($symbol == ')') ? TRUE : FALSE;
}