PHP Database Access Using Redis - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Database Access Using Redis - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Wednesday, June 12, 2019

PHP Database Access Using Redis

PHP Database Access


Using Redis

Problem

You want to use the Redis key-value store from your PHP program.

Solution

If you can install PECL extensions, install the redis extension and then use it as follows:

        $redis = new Redis();
        $redis->connect('127.0.0.1');
        $redis->set('counter', 0);
        $redis->incrBy('counter', 7);
        $counter = $redis->get('counter');
        print $counter;

If you can’t, use the Predis library:

        require 'Predis/Autoloader.php';
        Predis\Autoloader::register();

        $redis = new Predis\Client(array('host' => '127.0.0.1'));
        $redis->set('counter', 0);
        $redis->incrBy('counter', 7);
        $counter = $redis->get('counter');
        print $counter;

Discussion

Although the redis extension and Predis library differ in how they are installed and how you connect to a server, they behave similarly in many respects. Each gives you an object representing a connection to a Redis server (or a pool of Redis servers) and that object has methods corresponding to the different operations you can send to the server(s).

To install the redis extension, use the pecl command:

        pecl install redis

To install Predis, use pear:

        pear channel-discover pear.nrk.io
        pear install nrk/Predis

If you are using the Composer package manager, install Predis with a dependency string of "predis/predis".


No comments:

Post a Comment

Post Top Ad