Tutorials: Working with NoSQL Databases

Setting NoSQL Databases

In order to be able to query NoSQL databases (eg: Redis), you first need to open stdout.xml and make sure this tag exists within <listeners>:

<listener class="NoSQLDataSourceInjector"/>

then create a <server> tag (which will hold your connection settings), child of DEVELOPMENT_ENVIRONMENT tag (because credentials will be different on another environment), child of <nosql>, child of <servers> tag. Example:

<servers> <sql> <local> <server driver="redis" host="localhost"/> </local> </sql> </servers>

If your site uses multiple database servers for a single DEVELOPMENT_ENVIRONMENT, it is allowed to have multiple <server> entries there. To learn more how to configure this tag and drivers supported, check official documentation!

Querying NoSQL Databases

Querying NoSQL databases requires you completed setting NoSQL databases section!

Retrieving a Connection

If you have a single server per DEVELOPMENT_ENVIRONMENT, to get a connection, use:

$connection = Lucinda\NoSQL\ConnectionSingleton::getInstance();

If you are having multiple servers per DEVELOPMENT_ENVIRONMENT, use this instead

$connection = Lucinda\NoSQL\ConnectionFactory::getInstance(SERVER_NAME);

Where SERVER_NAME is value of "name" attribute at matching <server> tag.

Both will return a single Lucinda\NoSQL\Driver per session, reused until script ends and automatically closed afterwards (unless driver is apc/apcu, requiring no connections).

Running Statements

Once a connection is retrieved, you can run basic document database logic such as:

$connection->set(KEY, VALUE, EXPIRATION);

Example:

// saves a key named "foo" with value "bar" in DB that expires in 10 seconds $connection->set("foo", "bar", 10); // retrieves value of "foo" from DB $x = $connection->get("foo");

This works the same way as PDO, hiding complexities of driver used. If, however, basic operations are not enough and you need to work with actual vendor logic use:

$vendorDriver = $connection->getDriver();

then use vendor official documentation (eg: redis) to query that object.


Share