Hostingireland App on the App store and covered by silicon republic

 Development, Ios  Comments Off on Hostingireland App on the App store and covered by silicon republic
Oct 232011

I have been beavering away in on a native iOS app for our clients to use for managing their accounts, ordering new domains, sending support tickets and so on. And now its live an up on the app store and has been covered by silicon republic read it here and will also quite possibly be at least mentioned in the Sunday Business Post. I hope that in the future, we will see lots of people using this app and also that we can add and improve on its features.

I was quite excited about this app as it gave me the opportunity to build something that I knew would be useful and also that would definitely end up on the App Store. With a pre built audience, I also knew it would see use.
As my friends know, I have built several apps for iOS but have decided for one reason or another not to publish them to the app store, well at least not yet anyway. Seeing this app on the App Store has given me a lot of confidence to complete some of my own projects and get them up on the store too. Watch this space :)

Now for some boring programming stuff

For any interested, I am going to run through some of my thoughts and decisions made while creating this app.
Web Api

The first steps to building the app, after planning out its features, was to build the web api.I used PHP for this as this is the language used in the company for most programming tasks.

This app required strong security and also easy extensibility. The app makes each request via https and uses two layers of authentication and validation. Easy extensibility was achieved by creating a set of abstract class which took care of a lot of the common business logic but left the variables and base implementation up to its concrete children by forcing the override of several abstract methods. The abstract api method controller also implements a method controller interface. This means I can easily extend the Api to add new features/methods in the future.

The App

Often when building apps with lots of options and data, you feel the need to have UITabBarController as well as a UINavigationController. This isn’t a template in Xcode but can be easily achieved by creating a RootViewController that extends UINavigationController for each tab option and then adding this controllers as the UITabBars controllers. Maybe an example would be good.

RootViewController * accountView = [[[RootViewController alloc]initWithNibName:nil bundle:nil] autorelease];
accountView.tabBarItem.title = @"Account";
accountView.tabBarItem.tag = TAB_CONTROLLER_ACCOUNT;
accountView.tabBarItem.image = [UIImage imageNamed:@"111-user.png"];

//Add as tabbar view controllers

NSArray * controllers = [NSArray arrayWithObjects:accountView,domainRegView,supportView,productsView,moreView,nil];
self.tabBarController.viewControllers = controllers;

In the root view controller you then have a switch which would look at the tag of the tabbaritem and push on to the stack the appropriate UIViewController.

Other difficulties I faced in the app itself included allowing the app to cache certain api call responses and deciding how and when an api call response should be refreshed. To achieve this I created a cache manager which exposed several methods to allow a cache to be checked, set to refresh or a new cache to be created. The aim of the cache was to reduce the potential number of requests being sent to the web server and to reduce any latency in the app wherever possible.

Another important factor was allowing multiple web requests to be made from the app simultaneously and without locking up the UI. To do this I created an extension of NSOperation which performed the calls on background threads rather than the main UI thread. I also created a protocol with methods it would call on a delegate based on the type of response sent back by the api. To allow easy use, I created an api method factory class which which was a singleton and had a handle to a shared NSOperationQue.

Overall it was a great experience building this app

Objective C ASynchronous Http Request Wrapper

 Development, Ios  Comments Off on Objective C ASynchronous Http Request Wrapper
Oct 232011

So having worked on two apps now that required many requests to web servers to be made in the background, I decided to write a simple to use wrapper around the more complex parts which exposes what I hope is a clear api.

The basic concept is an extension to NSOperation overriding the methods:

- (void)start;
- (BOOL)isConcurrent;
- (BOOL)isFinished;
- (BOOL)isExecuting;

I aslo made some simple Http Request and response wrappers and a protocol for receiving the responses called HttpResponseDelegate

@protocol HttpResponseDelegate

- (void)requestResponseRecieved:(HttpResponse *)res;

- (void)requestResponseError:(HttpResponse *)res;
- (void)requestFailed:(NSError *)err;
- (void)request:(HttpRequest *)req AndOpCancelled:(HttpOperation *)op;

The wrapper will let you send both post and Get requests which are cancelable and will be performed on background threads; although it doesn’t yet allow for the posting of multipart data such as images, but I plan to add that in time. I know there are other libraries out there for this kind of thing, but I wanted to do it for myself as a personal experiment and project. I have put the code up on git hub. Feel free to use it as you wish Git Hub Repo

Basic Usage

Just to give a quick usage example:

in a viewController implementing the HttpResponseDelegate protocol you would do something along the lines of :

- (void)someMethod{
//this is a singleton class that manages adding ops to a single operation que
HttpSync * httpFactory = [HttpSync getSharedInstance];
HttpRequest * req = [[HttpRequest alloc]initWithUrl:@""];
HttpRequest * req2 = [[HttpRequest alloc]initWithUrl:@""];

//send some params
[req2 setParamWithKey:@"someparam" AndValue:@"somevalue"];

//change to POST req.method = HTTP_METHOD_POST;
//default method is GET

req.method = HTTP_METHOD_GET;
//make the operations possibly could add this functionality to the HttpSync class in future
HttpOperation * httpOp = [[HttpOperation alloc] initWithRequest:req AndResponseDelegate:self];
HttpOperation * httpOp2 = [[HttpOperation alloc] initWithRequest:req2 AndResponseDelegate:self];
[httpFactory sendOperation:httpOp];
[httpFactory sendOperation:httpOp2];
[req2 release];
[req release];
[httpOp release];
[httpOp2 release];


#pragma mark HttpResponseDelegate methods

- (void)requestResponseRecieved:(HttpResponse *)res{
if(res.responseCode == HTTP_RESPONSE_CODE_OK){
//do your thing get the content by using
NSData * resData = res.rawResponse;
NSString * resString = res.responseAsUTF8DecodedString;
//see the headers
NSDictionary * headers = res.responseHeaders;

//check the response code and respond accordingly

Gah objective c does not come out well on the blog. Hopefully you can follow it. Will be adding some improvements as I hope to use this library in some of my future projects.


I wanted to add a quick post about this as it was something which took me a while to figure out and so I hope it will be helpful to others.

Sometimes in an app. you want a UIButton to be pressed and remain selected. Now you can set the selected property to YES
, but this doesn’t keep the appearance of a selected button.

Now you could make a custom image for your button and use :

[button setBackgroundImage:[UIImage imageNamed:@”someimage.png”] forState:UIControlStateSelected];

However I found this way of doing it to be better, particularly, as with most coders, if you’re not a great fan on photoshop.

first add #import <UIKit/UIKit.h>

We can then use the graphics layer to alter the buttons appearance. My thanks to for pointing me in the right direction for this one:

- (void)controlButton:(UIButton *)sender

[[sender layer] setCornerRadius:8.0f];
[[sender layer] setMasksToBounds:YES];
[[sender layer] setBorderWidth:1.0f];

if (sender.selected == YES) {

[[sender layer] setBackgroundColor:[[UIColor lightGrayColor] CGColor]];

[[sender layer] setBackgroundColor:[UIColor whiteColor].CGColor];



Just wanted to add a quick tutorial on setting up PHPUnit on your mac.

First step:
Mac osX no longer comes with PEAR (PHP Extenstion Aplication Repository) installed and this is the easiest way, in my opinion to install and set up PHPUnit. So the the first step is to install PEAR

Open terminal and run:

curl > go-pear.php

next run the script

sudo php -q go-pear.php

You will next be given a list of options. The only one that needs to be changed is the install dir
set it to /usr/local

Press enter and it will finish installing PEAR. Next you will need to alter the php.ini file used by the default install of php on the mac. Run the following:

sudo cp /etc/php.ini.default /etc/php.ini

next we need to add the pear repo to the include path.

sudo nano /etc/php.ini
press ctrl w and type in include_path
change this from ;include_path = ".:/php/includes"
to include_path = ".:/php/includes:/usr/share/pear"
//restart apache
sudo apachectl restart

Now pear should be installed. So onto the PHPUnit.

sudo pear channel-discover
sudo pear install phpunit/PHPUnit

And that should be PHPUnit installed. So now onto netbeans. Fire up netbeans and then open prefrences -> php-> general and set the php interpretor to /usr/bin/php then go to unit testing and add /usr/local/bin/phpunit as your phpunit script. You may also want to add to your include path in netbeans /usr/local/share/pear/PHPUnit this will enable netbeans to read the class files and prompt you with auto completes.

Hope this helped.

The Power of Zend_Validate and Zend_Filter

 Development, Zend Framework  Comments Off on The Power of Zend_Validate and Zend_Filter
Sep 062011

I don’t know about you, but I find that sometimes coding html forms and the corresponding backend validation to be the typical type of “Boiler Plate” code that once you’ve done it and understand the principles, that you never really want to have to do it again.

Into the breach steps Zend_Frameworks’ Zend_Validate and also Zend_Filter. This set of classes can be used in conjunction with the Zend_Form_Element Classes and Zend_Form Class and makes validating forms almost a pleasure. Let me show you an example.

Often with a web form we need to validate that an email address is valid. So you might use a function such as:

filter_var($email, FILTER_VALIDATE_EMAIL)

And then redirect back with an error stored in the user’s session if it fails. However it gets a little more tricky when you also need to validate that the email address is unique to your database table.

public function validateUsersEmail(){
if(filter_var($this->email, FILTER_VALIDATE_EMAIL)){
//do query to check email address not already entered
//if no return true
return false;

However Zend Framework offers a set of very powerful filters. which means you can create a form email like so from within a class extending Zend_Form:

$handleElement = new Zend_Form_Element_Text("handle");
//Here is where the validator kicks in
$handDbValidator = new Zend_Validate_Db_NoRecordExists('siteusers','handle');
$handDbValidator->setMessage("That username already exists");
->addFilter(new Zend_Filter_Alnum(false))
->addFilter(new Zend_Filter_StripTags())
->addFilter(new Zend_Filter_StringTrim());

Now that looks like a lot of code. However there are several validators and also filters being applied to this element.

Here is the code for checking if a record exists and also to set the error message to report to the user

$handDbValidator = new Zend_Validate_Db_NoRecordExists('siteusers','handle');
$handDbValidator->setMessage("That username already exists");

Here we specify the table name and the field name to check and then add an error message if it fails.

Now the filters

So how often have you gone searching for the right regular expression to strip out all none alpha numeric characters from a string? Well I know I often forget the exact syntax and go searching. Zend Framework offers you a great set of Filters to apply to your form elements. In the above code you can see them at work in the following way:

->addFilter(new Zend_Filter_Alnum(false))
->addFilter(new Zend_Filter_StripTags())

These are fairly self explanatory but show what is possible using the Zend_Form Class along with filters and validators.

You can find out more on validators and also Filters by following the links. concept – hopes – and plan

 Ideas, startup stuff, thoughts and musings  Comments Off on concept – hopes – and plan
Sep 052011

So a while ago I wrote an article on scaling down. Where I spoke about the success of any individual being bound with the success of their community. Well at the time of writing, I was also, and still am, busy working on a new project. That project is

The Concept

The concept behind is to provide a place for the locals in a community to easily talk about and promote what they love, hate, and want to change in their local community. This can be done in a number of ways on the site: you can add a post, ask questions which other locals can answer and also set up, manage, organise and promote local projects, whether they be their own or community based. I have lots more ideas planned and would love to hear any feed back positive or negative.


A major hope of mine is that first and formost that people find the site offers them something useful and worthwhile, but also that local authorities, tds, councilors, businesses etc catch on to the site and see its potential for connecting and communicating with the locals that make up their constituencies and communities.

My ideal, my dream, perhaps, is to have locals communicating with each other regularly and talking about what is on their minds. I also want those with ideas, perhaps ideas they have had for a long time, but have felt they didn’t know how to get started, or that they wouldn’t be listened to, find others who share in their idea and so do more than get started, they actually make things happen; and for those with valuable local knowledge to share it by adding posts and answering the questions asked by others.

You can see a good example of how the site can work by taking a look at the waterford section of the site. This is my home county.


Over the coming months I am going to be working hard to try and promote in anyway that I can. I plan on writing to my local newspapers, perhaps submitting an editorial piece to them, and also contacting radio stations to try and gain some exposure. I also want to get in contact with my local council, politicians and businesses.

I will also be working hard on the site. I hope to improve it with each day/week and make it a great place to visit. If you have any ideas or thoughts on please don’t hesitate to contact me. You can use this blog, or via email at craig[at] you can also follow @locals_ie

I am a web and software developer by trade and so have plans to bring out a mobile app in the future at some point also.

If you like the idea of locals: tweet about it, like it on facebook, talk about it, but most of all become a local and get involved.

creating a request filter – allowing for /username

 Development, Zend Framework  Comments Off on creating a request filter – allowing for /username
Aug 302011

Often in modern websites, particularly social websites, the urls are in the format of This presents something of a problem for web apps that follow the MVC pattern and direct all requests through a single front controller that then dispatches the request to the correct controller based on the url or on a route set up in the app. Recently I have begun work on a website, and I wanted to implement a url pattern of . So how so we achieve this when we cannot properly map this using a route as the group name could be almost anything?
I achieve this by using a simple Zend plugin. Here is the code:

* Description of GroupFilter
* allows for urls to follow the format of
* sitename/group-name
* @author craigbrookes
class Application_Plugin_GroupFilter extends Zend_Controller_Plugin_Abstract {

public function preDispatch(Zend_Controller_Request_Abstract $request) {
$controller = $request->getControllerName();
$groupMapper = new Application_Model_GroupsMapper();
$group = $groupMapper->findRowByFieldsAndValues(array("url"=>$controller));




So in this code, I extend the Zend_Controller_Plugin_Abstract which provides several hook functions (functions which the parent or a controller will call on all plugins at certain times during execution)

The hook functions provided are:

  • routeStartup(): prior to routing the request
  • routeShutdown(): after routing the request
  • dispatchLoopStartup(): prior to entering the dispatch loop
  • preDispatch(): prior to dispatching an individual action
  • postDispatch(): after dispatching an individual action
  • dispatchLoopShutdown(): after completing the dispatch loop

In the above code I choose only to implement the preDispatch() which is past the instance of
Zend_Controller_Request_Abstract. From this request object I get the current controller which my be set to the name of a group. I then use my Mapper class and check if there is a group that responds to the controller name. Finally, if there is a group object found, then I set the controller to the Groups controller which can then take over. Other wise the request continues along its merry way. Got any other solutions or can see potential problems with my solution, please leave a comment and let me know.

For more information on plugins, I found this article to be quite useful.


nullI believe we should be doing everything we can to encourage an environment where small startup businesses have every possible chance to get off the ground and go from an idea to an actual business. I think it is vital to any real, lasting economic recovery. These types of businesses will in the future create a more healthy, robust and diversified economy.

There is one area in particular that I see as great way to cultivate a healthy startup environment in Ireland, and that is the area of office space.

It has struck me several times, while travelling around Ireland and around my own home city of Waterford, that there seems to be a whole lot of empty office space. This empty office space, is not newly empty, most, if not all of it, has been largely empty now for the best part of two years or more.

Waterford is not alone in this phenomena, wherever I have travelled in Ireland, these sad, empty shells are present on the landscape of any business park. It is as if they are destined to remain grim memorials of our recent past or perhaps simply as the scars of a well known tiger that turned on its keeper. You don’t have to stray far from the city center to find rows and rows of to let signs lamely hanging in the windows of these buildings; no doubt buildings which have been long forgotten by the appointed letting agent. These offices are not being let, and I would suggest wont be let for the foreseeable future. They are being wasted.

Now add to this mix the high number of unemployed people eager to get to work who, no longer able to find employment, are looking to set up something of their own, perhaps in a field they took interest in only as a hobby etc during the boom years, but now see potential for a business idea. Every effort should be being made to support these people that are working hard to try and start again; the entrepreneurial types who are building home grown, Irish businesses from the ground up.

Well these fledgling businesses need a place to work from. It is all well and good, working from home, but nothing really substitutes for a space in which you can bring people together for a single purpose, with no distractions and the tools with which to achieve your goals.
Also with a buildings full of these energetic, passionate and hard working people the effect will spread and infuse others, who are maybe a little unsure or disheartened, to take the first steps and begin putting together concepts and talking to people about their business ideas.

We do hear rhetoric from the politicians claiming they wish to help small businesses get started or continue to exist, and, while some things are being done to help get small businesses up and running, surely this expanse of empty office space offers a great opportunity to our enterprise boards and the government as a whole?

So here is my proposal: a young business, a startup, of under two years would have the opportunity to apply to the enterprise board for subsidized or even completely free office space. They would apply using a simple, but thought out business plan. The businesses that were successful, would be all offered office space in the same area, and perhaps with other business who had ideas in the same area? It’s that simple.

Landlords would begin renting now empty buildings. Businesses and jobs would begin to be created and the economy as a whole would benefit. Tell me I’m wrong, please!

Now I am aware that you can get grants etc from the enterprise board, but from speaking with people who have received these grants recently, this is a long and difficult process. What I am thinking of is something much more simple. It would be the case that if you could prove you were working hard on something, from home for example, and that your proposed business wasn’t simply a hobby, but actually had merit, then you would get space to work in. It may be shared space, or simply two desks in a room with other budding businesses. As long as there was access to broadband and general office equipment, I am sure it would be fine for most simple startup businesses. It seems amazing to me that this isn’t already being done and I would be delighted if someone told me it was already being done.
And after all, sure, we probably own half the building through NAMA etc anyway.

Abstract Zend Data Mapper Class for Zend Framework

 Development, Zend Framework  Comments Off on Abstract Zend Data Mapper Class for Zend Framework
Aug 232011

I have started a new project with a fellow programmer, Peter Fortune @pfortune. The project is a group organising tool, aimed at the Irish market and will be hosted under the domain

So when discussing this project, we decided to use Zend Framework as we both are very comfortable with PHP and I have used Zend Framework in the past. After working on the design of the database schema, it came to laying the ground work for the project. Building the models fell under my todo list and so I set to work.

So I spent a little time coming up with what I think is a reasonable Abstract class for the Applications data mapping classes to extend. I know quite a few developers prefer to use doctrine with Zend Framework, and when the project progresses, this may be something we will consider using also, but for the time being, I went with the inbuilt tools Zend_Db_Table_Abstract etc. So here is the class I ended up with. Please give me your thoughts and criticisms and point out any gaping errors.

$this->_model = $model;


public function setDbTable($dbTable)
if (is_string($dbTable)) {
$dbTable = new $dbTable();
if (!$dbTable instanceof Zend_Db_Table_Abstract) {
throw new Exception('you must pass a class that extends Zend_Db_Table_Abstract');
$this->_dbTable = $dbTable;
return $this;

* @return Zend_Db_Table_Abstract
* return concrete child
public function getDbTable()
if (null === $this->_dbTable) {
throw new Exception("no dbtable set");

return $this->_dbTable;

* @param Application_Model_RowAbstract $row
* @return array
* returns an array of concrete children extending Application_Model_RowAbstract
public function findAllByExample(Application_Model_RowAbstract $row)
//returns all public properties and their values in assoc array
$props = get_object_vars($row);
$sql = $this->getDbTable()->select();
foreach($props as $property=>$value){
if(!NULL == $value)
$sql->where(''.$property.' = ?',$value);

$rows = $sql->query()->fetchAll();
$ret = array();
foreach($rows as $row){
$ret[]= new $this->_model($row);
return $ret;


* @param Application_Model_RowAbstract $row
* @return Application_Model_RowAbstract
* returns a concrete child
public function findRowByExample(Application_Model_RowAbstract $row){
$props = get_object_vars($row);
$sql = $this->getDbTable()->select();
foreach($props as $property=>$value){
if(! NULL == $value)
$sql->where(''.$property.' = ?',$value);

$rows = $sql->query()->fetchObject($this->_model);
return $rows;

* @param Application_Model_RowAbstract $row
* chooses to save or update based on whether the primary key is set or not
public function saveUpdate(Application_Model_RowAbstract $row)
//get pri key from get_primary() public method added
//to concrete implimentation of Zend_Db_Table_Abstract
$prikey = $this->getDbTable()->get_primary();
$prikey = $prikey[1];
$data = get_object_vars($row);
$updateData = array();
foreach($data as $property=>$value){
if(!NULL == $value)
//$this->getDbTable()->update($updateData, ''.$prikey.'='.$row->$prikey.'');


* @param mixed $value
* @return Application_Model_RowAbstract
* the value is the value of the primary key set for the row
public function findWherePriKeyEquals($value){

$row = $this->getDbTable()->find($value);
$ret = $row->current();
return new $this->_model($ret->toArray());



so that’s it. As you can see you have most functionality there. You can create a dummy object and find all that match its values in the database. You can update and save an objects values
and you can find based on simple rules. All of this means that the concrete sub classes have a lot less work to do. Hope this is helpful.


The success of a community is vital to the lasting success of any individual within that community. This is something I hold as a core value and I sincerely hope that you do too.

As a product of your community and peers, successful communities will create more successful individuals; and in turn, an individual that holds his own interests and those of his community as being equal, or as close to equal as possible, will create more successful communities.

When I speak of community, I am referring to your locality, the place where you live. Your community is made up of the people in your favourite coffee shop, the teachers educating your children your neighbours and so on. Each member of your community will have an impact, whether directly or indirectly, on your outlook and help you form opinions on society and on how you, as an individual, fit in and should interact with it. They will inform your ideas on how society should be governed, what is acceptable and how it can be improved. So far so obvious, right?

Well the above leads me to a major issue I believe we are facing, and that is the problems caused by the ever expanding scale of our communities brought about by our ability to communicate across vast distances. This problem of scale is affecting every aspect of our lives. In business, the internet is giving companies easy and cheap access to markets that they would have never considered accessible previously. This in turn means that these companies are growing at an unprecedented scale, and their customer bases are immense* this of course erodes the importance of an individual customer. News agencies and charities can bring every tragic disaster to our living rooms, causing us to become increasingly numb to disaster, as an act of self preservation. Your time is important and it is impossible to care about, in a realistic way which motivates us to action, all that is presented to us on a daily basis. But this also must have a trickle down effect on the way in which we perceive those within our own communities which require charity, effect how we run our small to medium businesses and so on.

With such large scale in our everyday lives, it becomes difficult to feel truly connected. We give money to charity but do not see any of the impact which that action had, we help a customer but again see no impact of having solved their problem. Seeing the positive impacts of our actions is essential to continued motivation to perform further actions. To this end, I think it is essential that we find ways to scale down, make things more personal and the effects of good action more visible.

So if we accept, and perhaps you don’t, that we should try to find ways in our lives to try and scale down and make the impact of our own actions more visible, then how can this be achieved?
Well I intend to go into that in my follow up post coming soon.

* read groupon, amazon etc

© 2012 Craig Brookes Suffusion theme by Sayontan Sinha