Quick Start

Note: This tutorial assumes you have read and finished Installing SimpleCache

1. Choose a driver

The first step is to select a driver, out of the box SimpleCache supports: APC, Memcached and Redis. It also comes with a handy file driver in-case you can't or don't want to rely on external software!

2. Initializing SimpleCache

To initialize SimpleCache we must provide it with a driver and, in some cases, a list of options for that driver. As I've chosen to use the File driver I'll need to provide it with a dir option.

<?php
require_once 'vendor/autoload.php';

use J0sh0nat0r\SimpleCache\Cache;
use J0sh0nat0r\SimpleCache\Drivers\File;

$options = [
  'dir' => 'cache'
];

$cache = new Cache(File::class, $options);

There's a little extra going on here so lets break it down:
First we imported the Cache class (the bread n' butter of SimpleCache)
Then, we imported the File class from the Drivers namespace, this is will serve as a back-end for the Cache class
Finally, we created a variable to hold the options for the driver ($options) and then instantiated the Cache class! Simple, right? Further steps will assume you have an instance of SimpleCache stored in $cache.

3. Storing Items

All good cache systems provide a way to store data, SimpleCache is no different! The simplest way to store data is with the store function, used like so:

<?php
$cache->store('foo', 'bar');

That's it! foo was cached for Cache::$DEFAULT_TIME (which defaults to 3600).
What if we want to store foo for only 30 seconds though? Simply pass the desired storage time in seconds as the third argument of store, e.g:

<?php
$cache->store('bar', 'baz', 30); // True

SimpleCache also handles object serialization and de-serialization:

<?php
$user = [
  'id' => 1,
  'name' => 'Josh',
  'email' => '[email protected]'
];

$cache->store('users-' . $user['id'], $user); // True

$user === $cache->get('users-' . $user['id']); // True

4. Retrieving Items

Retrieving data is trivial (as you may have noticed in the storage example):

<?php
$cache->store('foo', 'bar'); // True

$cache->get('foo'); // bar

In the case that nothing is found for the given key null will be returned, but that can easily be changed:

<?php
$cache->store('foo', 'bar', 10); // True

sleep(11):

$cache->get('foo', 'Couldn\'t find foo!!!'); // Couldn't find foo!!!

5. Removing Items

Removing an item is as simple as calling the remove method

<?php
$cache->store('foo', 'bar'); // True

$cache->has('foo'); // True

$cache->remove('foo'); // True

$cache->has('foo'); // False

Bang, and the item is gone!