Using memcache and Zend_Cache

Probably one of the more useful things you can do with memcache is drop it into Zend Framework. Here’s how I did that.

Following on from the previous post, here is an example of how you can set up memcache to serve as a cache for your Zend project.

I like to use the method style of bootstrapping my application, so here’s the function that builds the cache for me.

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

/**

* Set up caching using memcache

*

* @return void

**/

protectedfunction_initMemcache()

{

if(extension_loaded('memcache'))

{

// Configure caching backend strategy

$cacheBackend=newZend_Cache_Backend_Memcached(

array(

'servers'=>array(

array(

'host'=>'127.0.0.1',

'port'=>'11211'

)

// Other servers here

),

'compression'=>true,

'compatibility'=>true

)

);

// Configure caching frontend strategy

$cacheFrontend=newZend_Cache_Core(

array(

'caching'=>true,

'cache_id_prefix'=>'MyApp_',

'write_control'=>true,

'automatic_serialization'=>true,

'ignore_user_abort'=>true

)

);

// Build a caching object

$memcache=Zend_Cache::factory($cacheFrontend,$cacheBackend);

Zend_Registry::set('cache',$memcache);

}else{

// Handle a non-existent extension here

}

}

Originally, I was getting the “Memcache::addServer function expects at most 6 parameters, 8 given” warning. To force Zend to play nice with memcache (and send the right parameter count), you need to make sure you have the compatibility option set to true in the backend options array.

Here’s an example on how to use:

PHP

1

2

3

4

5

6

7

8

$cache=Zend_Registry::get('cache');

if(!$request=$cache->load('dataset')){

$request=LargeQueryOrDataset();

$cache->save($request,'dataset');

}

var_dump($request);

Hope this helps in getting started with Zend_Cache (even on a technology as old as memcache).