Category: Programming

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).

Titanium Appcelerator is a pretty nifty tool. Here’s a small data manager object that looked after my external requests.

I was tinkering with Appcelerator recently, and came upon the need to build a data manager to shoot off requests in a bit of a “fire-and-forget” sort of way. I created this global object I could channel requests into. My particular server always replied with JSON, so you can tweak this for whatever data your remote server will return.

JavaScript

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

varDataManager={

send:function(toWhere,data,callback,context)

{

// Fail

if(!toWhere){

returnfalse;

}

// Defaults

data=data||{};// The data to send to the server

callback=callback||function(_r){return_r;};// The callback. If none is supplied, will just return the result

context=context||null;// The object that 'this' will refer to in the callback

if(Ti.Network.online){

varXHR=Ti.Network.createHTTPClient({

onload:function(){

varresult=JSON.parse(this.responseText);

returncallback.apply(context,[result]);

},

onerror:function(){

varresult=JSON.parse(this.responseText);

alert('There was an error with the connection. Please try again later.');

Appcelerator has sped up development in key areas tremendously, but at the cost of some flexibility and code bloat. It’s worth keeping an eye on, as each release is leaps and bounds ahead of its predecessor.

PHPFairly easy to learn, and with an improving OO model, Web development will only get better. Syntax is pretty straight forward and it’s easy to get something working relatively quickly.

Visual BasicVery simple syntax, and a good introductory language for learning Windows programming.

C/C++I like C (and C++) because you can do with it what you will. There’s a lot of flexibility and room to move for whatever problem you have.

JavaIt has a similar syntax to C, but automatic garbage collection makes me weep tears of joy.

JavascriptOne of my favourite aspects of web development is putting on my Javascript hat and adding very slick functionality to my site. Simple syntax and a lot of power for overriding default objects.

Objective-CVery quick to learn the basic syntax, and it forces a separation of code into conceptual pieces that I agree with.

That exercise is actually enlightening. I think focussing on the strengths of a particular language allows you to leverage it for maximum effectiveness. I’m fairly sure I’ve picked up more languages than this in the past, but not with enough experience for any sort of nice opinion. Perhaps next time I’ll just bitch and moan about all the languages I’ve used.

Getting Zend to return JSON data can be tricky at times. The JSON helper likes to send the ‘official’ JSON header (application/json), and most browsers are treating that as a download link, resulting in no data to the client and an unfortunate download box.

To bypass this default behaviour, you’ll need to tell the controller how to serve your JSON data:

PHP

1

2

3

4

5

6

7

8

9

10

11

12

// In your controller

publicfunctionoutputAsJSON()

{

$content=$some_var;

$this->getResponse()

->setHeader('Content-Type','text/html')

->setBody(json_encode($content))

->sendResponse();

exit;

}

The key part of this stub is the exit; line. It prevents the view renderer from sending anything, keeping your JSON data intact. Note: json_encode and json_decode only works from PHP version 5.2.1

To output all of your view’s variables in this way, replace $some_var; with:

PHP

1

json_encode($this->view->getVars());

Hopefully this saved someone a headache or two when dealing with Zend’s puzzling JSON implementation.

In the first part of this tutorial, we set up a pair of simple views in Interface Builder that we switched between modally. In this tutorial, we’ll make them somewhat useful and pass data between them using delegates.

The concept of protocols and delegates is an important and somewhat complex one, but I like to think of it in these simplified terms:

Basically, the object that implements our protocol agrees to implement the methods of that protocol. In the case of this tutorial, we’ll be connecting the modal view with our main view using a delegate.

Firstly, we’ll create the interface elements for our project. Open the ModalViewExampleViewController XIB file and create a button and a label as shown.

Jump to Interface Builder and be sure to link the new elements with the properties we defined. Refer to Part 1 of this tutorial for a guide on how to do that.

The next step is key. We will create a basic protocol and then assign a delegate. Open up ModalViewExampleViewController.h and add this:

Objective-C

1

2

3

4

5

6

// ModalViewExampleViewController.h

@protocolModalViewDelegate

-(void)didReceiveMessage:(NSString*)message;

@end

We then tell ModalViewExampleViewController to implement this protocol:

Objective-C

1

2

// ModalViewExampleViewController.h

@interfaceModalViewExampleViewController: UIViewController

We also need to add the protocol’s method to the main implementation:

Objective-C

1

2

3

4

// ModalViewExampleViewController.m

-(void)didReceiveMessage:(NSString*)message{

}

Once we have these in place, the next step is to set up a reference between the two views. What we will do is define a delegate inside of SampleView so that we can send messages to it.
Include the protocol in ModalViewExampleViewController.h and add the reference:

Objective-C

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

// SampleViewController.h

@protocolModalViewDelegate;

@interface SampleViewController : UIViewController{

iddelegate;

UIButton*dismissViewButton;

}

@property(nonatomic,assign)iddelegate;

@property(nonatomic,retain)IBOutletUIButton*dismissViewButton;

-(IBAction)dismissView:(id)sender;

@end

Be sure to synthesize the delegate in SampleViewController.m, and include the necessary header files.

Objective-C

1

2

3

4

5

6

7

8

#import "SampleViewController.h"

#import "ModalViewExampleViewController.h"

@implementationSampleViewController

@synthesizedismissViewButton;

@synthesizedelegate;

...

So far we have defined a protocol inside of our parent view, and defined a delegate in our modal view. The next step is to link them together and make them useful.
Firstly, we’ll write the functions that will handle the messages. Replace the original definition of didReceiveMessage with this:

What we’ve done is create a SampleView object and assigned its delegate to be the parent view. That is, the parent view will be handling messages sent by SampleView.
Open up SampleViewController.m and add the code to send the message.

Objective-C

1

2

3

4

5

6

// SampleViewController.m

-(IBAction)dismissView:(id)sender{

[delegate didReceiveMessage:@"Hello World"];

[self dismissModalViewControllerAnimated:YES];

}

Compile the app and run it. You should be able to see the text “Hello World” passed from one view to another once you dismiss your modal view with delegate. You can extend this any way you like with additional controls on the modal view, such as sliders or text input.

The connection would initialize and then run without a hitch. As I was hoping to port the app over to the iPad, I decided to test it using the iPad simulator under 3.2. However, once the app hit [c start];, I immediately got a EXC_BAD_ACCESS exception and the app crashed.

On further inspection, it seems as though the app will obey the startImmediately boolean on an iPhone device, but is strangely ignored on an iPad. I gave the documentation a read-through, and I couldn’t find anything of the sort.

A somewhat simple but annoying work around involved starting the NSURLConnection request immediately and removing [c start];:

In your iPhone app, you’ll probably be spending most of the time pushing new view controllers to the stack in order to show screen flow. Sometimes, though, you just want to popup a screen for quick display or input.

Here’s a quick demo/tutorial on the different standard modal views offered by iOS, including a simple way of passing generic string data back to the parent view. I’m assuming basic knowledge of iPhone programming, so feel free to skim if you’re comfortable.

First up, create a new Xcode View-Based application. I named mine “ModalViewExample”. Open up the NIB file “ModalViewExampleViewController.xib” and drag four buttons onto the screen as shown.

Ok, so now we have some buttons declared in our class, and some buttons dropped into the interface. At this point, your app has no idea what the relationship is. We’ll set these relationships in Interface Builder.

Switch back to your NIB file, and select “File’s Owner” in the NIB Object Window. Select the Connections Inspector tab, and drag a connection from the hollow point to the Button object in your View. You can see what I mean in the screenshot below. Repeat for the other buttons on the page.

Basically, what we’ve told Xcode to do is relate the code-based objects with the interface objects we created. This allows them to pass messages back and forth.

The next step is to actually assign methods to the click events. Go back to your ModalViewExampleViewController.h file and add these methods:

Objective-C

1

2

3

4

-(IBAction)showDefault:(id)sender;

-(IBAction)showFlip:(id)sender;

-(IBAction)showDissolve:(id)sender;

-(IBAction)showCurl:(id)sender;

You’ll also need to implement them in ModalViewExampleViewController.m:

Objective-C

1

2

3

4

5

6

7

8

9

10

11

-(IBAction)showDefault:(id)sender{

}

-(IBAction)showFlip:(id)sender{

}

-(IBAction)showDissolve:(id)sender{

}

-(IBAction)showCurl:(id)sender{

}

We now have definitions for buttons, and the actions to go with them. To connect them, go to Interface Builder. Select one of your buttons and drag a relationship between the “Touch Up Inside” event in the Connections Inspector and the First Responder in the Object Window. Select the name of the method you created.

After connecting all the buttons to their relative objects and actions, you’ll actually need to make the app do something. This is where we will define a modal view to present to the user.

Add a new UIViewController subclass with XIB to your project. I named mine “SampleViewController”. Open the XIB in Interface Builder and drag a new button onto the screen.

Once you’ve done that, create an IBOutlet for the button and define an action as above.

Objective-C

1

2

3

4

5

6

7

8

9

10

11

// SampleViewController.h

@interface SampleViewController : UIViewController{

UIButton*dismissViewButton;

}

@property(nonatomic,retain)IBOutletUIButton*dismissViewButton;

-(IBAction)dismissView:(id)sender;

@end

Be sure to go to Interface Builder and assign the connections as you did above. Once that’s done, you’ll need to synthesize and release the dismissViewButton object in SampleViewController.m as you did in ModalExampleViewController.m.

Assuming all your connections are in place, it’s time to actually do something with them. Switch to your ModalViewExampleViewController class and replace your previous method definitions with the following code. Also be sure to add #import “SampleViewController.h” to the top of your definition in order to expose SampleView to your class.

Let’s take a very quick look at what we’re doing. First, we define an instance of the new SampleViewController class. We then give it a modal transition style, based on the values found in the UIViewController documentation. Sending it to the front is as easy as using presentModalViewController:animated: Take note that you should probably use the navigation controller to push modal views if you have one. (i.e. [self.navigationController presentModalViewController:animated:]).

To finish up, we’ll need to code a way to dismiss the modal view once it’s presented to the user. Jump to the SampleViewController class and add this code:

Objective-C

1

2

3

-(IBAction)dismissView:(id)sender{

[self dismissModalViewControllerAnimated:YES];

}

Once that’s in place, build and run the project. You should be able to click through the buttons and check out the range of different modal views iOS has to offer. Note that the page curl only works in iOS 3.2 or greater. If you’re compiling for lower versions, you’ll just get the default slide up animation.

In Part 2, we’ll add a delegate in order to pass values between the modal and non-modal views.

What this snippet does is initialise two related caches – a core cache, and a page cache. The core cache (in this instance) is attached to our database table abstract class, which allows results to be stored as serialized strings. The page cache is invoked whenever template output is due to occur, and saves pre-rendered HTML for immediate output.