Maison  >  Article  >  développement back-end  >  Débuter avec PHP plus Redis et des applications simples

Débuter avec PHP plus Redis et des applications simples

不言
不言original
2018-04-13 16:05:521619parcourir

Le contenu de cet article est de partager avec vous l'introduction et l'application simple de PHP et redis. Il a une certaine valeur de référence. Les amis dans le besoin peuvent s'y référer

1. Environnement expérimental : win10 + redis3 .2 + php7
2. Installation des outils de gestion graphique php-redis / redis /redis, etc., sautez cette étape
3. Type de données redis couramment utilisé, pas d'explication détaillée
Référence : http://www.runoob.com/redis/r...
4. PHP + mysql + application simple redisNom de la base de données : redis Table de données : redis_user
Simuler l'opération PHP Mysql + opération redis CURD

1. Fichier de configuration config.php

<?php
$config = array(
    &#39;mysql&#39;=>array(
        &#39;host&#39;=>&#39;127.0.0.1&#39;,
        &#39;user&#39;=>&#39;root&#39;,
        &#39;pass&#39;=>&#39;root&#39;,
        &#39;dbname&#39;=>&#39;redis&#39;,
        &#39;prefix&#39;=>&#39;redis_&#39;
    ),
    &#39;redis&#39;=>array(
        &#39;host&#39;=>&#39;127.0.0.1&#39;,
        &#39;port&#39;=>6379
    )
);
fichier d'entrée index.php , Lorsque vous utilisez MySQL, veuillez utiliser l'ID de clé primaire

<?php
reqiure_once(&#39;Mysql.php&#39;);

//增加数据
// echo Mysql::getInstance()->table(&#39;user&#39;)->insert([&#39;user&#39;=>&#39;张三&#39;,&#39;pass&#39;=>md5(&#39;123456&#39;),&#39;create_time&#39;=>date(&#39;Y-m-d H:i:s&#39;)]);

//删除数据
// echo Mysql::getInstance()->table(&#39;user&#39;)->where(array(&#39;id&#39;=>30))->delete();

//查看单条数据
// $data = Mysql::getInstance()->table(&#39;user&#39;)->where(array(&#39;id&#39;=>&#39;30&#39;))->find();
// print_r($data);

//查找所有数据
// $all = Mysql::getInstance()->table(&#39;user&#39;)->field(&#39;id,user&#39;)->select();
$all = Mysql::getInstance()->table(&#39;user&#39;)->select();
print_r($all);

//修改数据
// echo Mysql::getInstance()->table(&#39;user&#39;)->where(array(&#39;id&#39;=>30))->update([&#39;user&#39;=>&#39;张三adfadfasdf11111111&#39;,&#39;pass&#39;=>md5(&#39;123456aaa&#39;)]);
?>

Débuter avec PHP plus Redis et des applications simples
Débuter avec PHP plus Redis et des applications simples
Débuter avec PHP plus Redis et des applications simples

Base de données MySQL.php et fichier d'opération redis

<?php
class Mysql
{
    static  $instance;
    private $conn;
    private $redis;
    private $options = array();


    //单例模式
    private function __construct()
    {
        error_reporting(E_ALL^E_NOTICE^E_WARNING);
        require_once(__DIR__.&#39;/Config.php&#39;);
        $conn = mysqli_connect($config[&#39;mysql&#39;][&#39;host&#39;],$config[&#39;mysql&#39;][&#39;user&#39;],$config[&#39;mysql&#39;][&#39;pass&#39;],$config[&#39;mysql&#39;][&#39;dbname&#39;]);
        if(mysqli_connect_errno($conn)) {
            echo "连接Mysql失败:".mysqli_connect_error();
            exit;
        }
        mysqli_query($conn,&#39;set names utf8&#39;);
        $this->options[&#39;prefix&#39;] = $config[&#39;mysql&#39;][&#39;prefix&#39;];
        $this->conn = $conn;
        $this->redis = new Redis();
        $this->redis->connect($config[&#39;redis&#39;][&#39;host&#39;],$config[&#39;redis&#39;][&#39;port&#39;]);
    }

    //获取对象实例
    static function getInstance()
    {
        if(self::$instance) {
            return self::$instance;
        } else {
            self::$instance = new self();
            return self::$instance;
        }
    }

    //设置表名
    public function table(string $table)
    {
        $this->options[&#39;table&#39;] = &#39;`&#39;.$this->options[&#39;prefix&#39;].$table.&#39;`&#39;;
        return $this;
    }

    //设置redis键名
    public function redis(string $key)
    {
        $this->options[&#39;key&#39;] = $key;
        return $this;
    }

    //设置条件
    public function where(array $where)
    {
        $condition = &#39;&#39;;
        $and = count($where) > 1 ? &#39; and &#39; : &#39;&#39;;
        foreach ($where as $key => $value) {
            if($key == &#39;id&#39;) {$this->options[&#39;user_id&#39;] = $value;}
            if(strpos($key,&#39;:&#39;)) {
                $arr = explode(&#39;:&#39;, $key);
                $condition .= &#39;`&#39;.$arr[&#39;0&#39;].&#39;` &#39;.$arr[&#39;1&#39;]. &#39; "&#39;.$value.&#39;" &#39; . $and ; 
            } else {
                $condition .= &#39;`&#39;.$key.&#39;` = &#39; .&#39;"&#39;.$value.&#39;"&#39; .$and  ; 
            }
        }
        $this->options[&#39;where&#39;] = rtrim($condition,&#39; and &#39;);
        return $this;
    }

    //设置字段
    public function field(string $field)
    {
        $this->options[&#39;field&#39;] = $field;
        return $this;
    }
    
    //增加数据
    public function insert(array $data)
    {
        $key = &#39;`&#39;.implode(&#39;`,`&#39;, array_keys($data)).&#39;`&#39;;
        $value = &#39;"&#39;.implode(&#39;","&#39;, $data).&#39;"&#39;;
        $sql = "insert into {$this->options[&#39;table&#39;]} (".$key.") values (".$value.");";
        if( mysqli_query($this->conn,$sql) ) {
            $user_id = $this->conn->insert_id;
            $data[&#39;id&#39;] = $user_id;
            //以hash类型存储
            $this->redis->hset($this->options[&#39;table&#39;],$user_id,json_encode($data));
            return $user_id;
        } else {
            return 0;
        }
    }

    //删除数据
    public function delete()
    {
        $where = $this->options[&#39;where&#39;] ? $this->options[&#39;where&#39;] : &#39;1&#39;;
        $sql = "delete from {$this->options[&#39;table&#39;]} where {$where};";
        if(mysqli_query($this->conn,$sql)) {
            $this->redis->hdel($this->options[&#39;table&#39;],$this->options[&#39;user_id&#39;]);
            return 1;
        } else {
            return 0;
        }
    }

    //修改数据
    public function update(array $data)
    {
        $condition = &#39;&#39;;
        $where = $this->options[&#39;where&#39;] ? $this->options[&#39;where&#39;] : &#39;1&#39;;
        foreach ($data as $key => $value) {
            $condition .= ", `".$key."` = &#39;".$value."&#39;";
        }
        $condition = substr($condition, 1);
        $sql = " update {$this->options[&#39;table&#39;]} set {$condition} where {$where} ; ";
        if(mysqli_query($this->conn,$sql)) {
            $hashData = (array)json_decode($this->redis->hget($this->options[&#39;table&#39;],$this->options[&#39;user_id&#39;]));
            foreach ($data as $key => $value) {
                $hashData[$key] = $value;
            }
            $this->redis->hset($this->options[&#39;table&#39;],$this->options[&#39;user_id&#39;],json_encode($hashData));
            return 1;
        } else {
            return 0;
        }
    }


    //查找单条数据
    public function find()
    {
        $field  = $this->options[&#39;field&#39;] ? $this->options[&#39;field&#39;] : &#39;*&#39;;
        $where = $this->options[&#39;where&#39;] ? $this->options[&#39;where&#39;] : &#39;1&#39;;
        if($this->options[&#39;user_id&#39;]) {
            echo &#39;从redis获取数据<pre class="brush:php;toolbar:false">&#39;;
            $data = (array)json_decode($this->redis->hget($this->options[&#39;table&#39;],$this->options[&#39;user_id&#39;]));
            if($field != &#39;*&#39;) {
                $field = explode(&#39;,&#39;, $field);
                foreach ($field as $value) {
                    $arr[$value] = $data[$value];
                    $arr[&#39;typ&#39;] = &#39;redis&#39;;
                }
                return $arr;
                
            }
            return $data;
            
        } else {
            
            $sql = " select {$field} from {$this->options[&#39;table&#39;]} where {$where}; ";
            if($query = mysqli_query($this->conn,$sql)) {
                return mysqli_fetch_assoc($query);
            } else {
                return array();
            }
        }
    }
    //查找所有数据
    public function select()
    {
        $data = array();
        $field  = $this->options[&#39;field&#39;] ? $this->options[&#39;field&#39;] : &#39;*&#39;;
        $hashData = $this->redis->hgetall($this->options[&#39;table&#39;]);
        if($hashData) {
            if($field != &#39;*&#39;) { 
                $field = explode(&#39;,&#39;, $field);
            }
            foreach ($hashData as $key => $value) {
                $data[$key] = array();
                $values = (array)json_decode($value);
                if($field != &#39;*&#39;) {
                    foreach ($field as $k => $v) {
                        $data[$key][$v] = $values[$v];
                    }
                }else{
                    $data[$key] = $values;
                }
            }
            echo &#39;从redis获取数据<pre class="brush:php;toolbar:false">&#39;;
        } else {
            $sql = " select {$field} from {$this->options[&#39;table&#39;]} ; ";
            if($query = mysqli_query($this->conn,$sql)) {
                while ($row = mysqli_fetch_assoc($query)) {
                    $data[] = $row;
                }
            }
        }
        return $data;
    }

    

    public function __destruct()
    {
        mysqli_close($this->conn);
    }
}

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn