Loading...
PHP/MySQL | memcached.php - MemCache без расширений
Мемкэш давно бы уже пора добавить в список официальных расширений PHP, постоянно пересобирать самому не охота, и к тому же классическое расширение Memcache не доступно под PHP 7. Поэтому я решил реализовать клиент мемкэша на чистом PHP, благо протокол у него очень простой. По совместительству, библиотека может быть telnet клиентом =)

https://bym.guru/downloads/view/77396

Пример кода(бумас порезал всё экранирование, поэтому качать по линку выше, это лишь пример)
<?php
/*
* MemCached client in pure PHP
* This library is NOT compatible with official memcache extension implementation.
* Also, this library can be used as simple telnet client =)
*
* ©2019 monobogdan. All rights reserved.
*/

// Result codes
const MEMCACHED_STORED = 0;
const MEMCACHED_NOTFOUND = 1;
const MEMCACHED_ERROR = 2;
const MEMCACHED_DELETED = 3;

const MEMCACHED_MAXLENGTH = 32768;

$__memcache_handle = null;

/*
* Connect to memcached compatible server using TCP.
* $addr - Server address
* $port - Server port, by default 11211
*
* Returns: true on succeful, false otherwise
*/
function memcache_connect($addr, $port = 11211)
{
global $__memcache_handle;

$__memcache_handle = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if(!$__memcache_handle)
{
trigger_error("Failed to create TCP socket");

return false;
}

$result = socket_connect($__memcache_handle, $addr, $port);

if(!$result)
trigger_error("Connection failed to remote server $addr:$port");

return $result;
}

/*
* Issue $cmd command to memcached
* You can obtain list of available commands in official wiki
*
* Note: Be aware with newlines, telnet protocol relies on rn as end sequence, not
*/
function memcache_command($cmd)
{
global $__memcache_handle;

if($__memcache_handle)
{
socket_write($__memcache_handle, $cmd);
return socket_read($__memcache_handle, MEMCACHED_MAXLENGTH);
}

return false;
}

/*
* Set key $key value $value
* Note: If key contains spaces, they will be replaced to _
*
* Returns: MEMCACHED_STORED on succeful, or MEMCACHED_ERROR otherwise
*/
function memcache_set($key, $value, $expires = 0)
{
$len = strlen($value);
$key = str_replace(" ", "_", $key);

$ret = memcache_command("set $key 0 $expires $lenrn$valuern");

return $ret == "STORED" ? MEMCACHED_STORED : MEMCACHED_ERROR;
}

/*
* Get key $key value
*
* Returns: Key value, or empty string if value doesn't exist
*/
function memcache_get($key)
{
$ret = memcache_command("get $keyrn");
$arr = explode("rn", $ret);

if(sizeof($arr) > 1)
$arr = array_slice($arr, 1, -2);

return implode("rn", $arr);
}

/*
* Flush all keys
*
* Returns: Nothing
*/
function memcache_flush()
{
memcache_command("flush_allrn");
}

/*
* Close connection to memcached server, if there is already connection
*/
function memcache_close()
{
global $__memcache_handle;

if($__memcache_handle)
{
socket_close($__memcache_handle);

$__memcache_handle = null;
}
}


Пример работы:
<?php
function fetchUser($user)
{
if($usr = memcache_get("usr_$user"))
return unserialize($usr);

$usr = mysql_query("SELECT * FROM users WHERE name='$user'");

if($usr)
{
$ret = mysql_fetch_array($usr);
memcache_set("usr_$user", serialize($ret));

return $ret;
}

return null;
}


________
посл. ред. 20.04.2019 в 15:42; всего 3 раз(а); by monobogdan
monobogdan, бд можно выбросить?)
CaMnoCe6e, незя, мемкэш не персистентный =)
Хотя конечно, его, как и редис можно использовать как простую NoSQL БД, но это не особо эффективно, всё таки он для кэшей предназначен.
const только в классе актуально, вне класса define используют )
Сибирский, без разницы, под капотом все равно define вызывается
________
посл. ред. 20.04.2019 в 11:18; всего 1 раз(а); by monobogdan
monobogdan, чем memcached не угодил? Какой классический под php 7 недоступно?
419236368, не захотел, memcache
monobogdan, вообще в классе реализовать удобней было бы, но суть ясна. Просто костыль этот вряд ли может пригодиться. И, в php 7 есть MemCache и MemCached просто собирать надо сразу с ними. И еще момент, кому они нужны? ))
monobogdan, где это оно недоступно? =-O
419236368, https://bugs.php.net/bug.php?id=72887

Note that the Memcache 3.0.8 module DOES NOT WORK WITH PHP 7 (or higher)

________
посл. ред. 20.04.2019 в 11:23; всего 1 раз(а); by monobogdan
Онлайн: 2
Время:
Gen. 0.1052
(c) Bym.Guru 2010-2025