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 http://cocoawithlove.com/ 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]];

}else{
[[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 http://pear.php.net/go-pear.phar > 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.
Run:

sudo pear channel-discover pear.phpunit.de
//then
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.

 

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");
$handleElement->setLabel("Username")
->setRequired(TRUE)
->addValidator("NotEmpty",TRUE)
->addFilter(new Zend_Filter_Alnum(false))
->addFilter(new Zend_Filter_StripTags())
->addValidator($handDbValidator)
->addFilter(new Zend_Filter_StringTrim());
->setOptions(array("size"=>"35","maxlength"=>"10","class"=>"textinput",
"placeholder"=>"Username"))

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.

 

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 locals.ie.

The Concept

The concept behind locals.ie 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.

Hopes

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.

Future

Over the coming months I am going to be working hard to try and promote locals.ie 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 locals.ie please don’t hesitate to contact me. You can use this blog, or via email at craig[at]locals.ie 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.

 

Often in modern websites, particularly social websites, the urls are in the format of http://somesite.com/username. 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, groups.ie and I wanted to implement a url pattern of http://groups.ie/the-group-name . 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));

if(!$group->isEmpty()){

$request->setControllerName("group");
}
}

}

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.

 

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 http://groups.ie.

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.


/**
* @author Craig Brookes
*
* All concrete Data Mapper classes for the application
* should extend this base class
*/

abstract class Application_Model_RowMapperAbstract
{

/**
*
* @var Zend_Db_Table_Abstract
*/
protected $_dbTable;
protected $_model;

/**
*
* @param String $tableName
* @param String $model
* sets up concrete extension of Zend_Db_Table_Abstract to be queried
*/
public function __construct($tableName, $model = "stdClass") {
$this->setDbTable($tableName);
$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);
}

$sql->limit(1);
$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);
if(isset($row->$prikey)){
//update
$updateData = array();
foreach($data as $property=>$value){
if(!NULL == $value)
$updateData[$property]=$value;
}
print_r($updateData);
//$this->getDbTable()->update($updateData, ''.$prikey.'='.$row->$prikey.'');
}else{
//insert
$this->getDbTable()->insert($data);
}

}

/**
*
* @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

 

Before I begin this post, I want to lay a little ground work to show where I am coming from. I have no degree in any *”ology” and these ramblings reflect only my own musings. I am an avid futurist and technologist, in particular, web technologies. I am a believer in its ability to change the future in major ways, largely for the good, as it has already done over and over.

You always know when things are changing because people are talking about that which is in flux. And we are talking now more than ever about technology, progress and in particular the web and how it integrating with our lives.

I found myself happy to hear of schools introducing the iPad to classrooms replacing heavy, expensive text books. More information on this can be found here at ipadinschools. I still think that this is a wonderful change, but it got me thinking about where we may be heading.

What will happen to the physical things? The books, CDs, photographs, newspapers etc. And in the process of replacing them, what is it that we risk losing?

Does a physical photograph mean more, and have more value than its digital counterpart? Does a physical book have more value than a book downloaded to your tablet? I think for the large part the answer is a resounding no, but occasionally it is a yes.

My family has boxes full of photographs and attics full of “stuff”, very few of these items have any real meaning other than to map out the past as a timeline represented as things. This can be achieved far better in the digital realm; and in my opinion, the digital realm provides more relevance and connection, particularly in a spatial/temporal sense.

But there is something to be said about having and holding something which has had time and craft put into it through purely physical interaction. A physical object can create the sense of a physical connection with the maker of the object. When I hold a scrapbook, made by my partner or hold a drawing done by my daughter, I know that they have held, touched and created this object and that means something; and I have yet to feel that “something” from their digital counterparts. So perhaps the first thing lost is the tactile properties of an actual object. Feeling and touching that shared object adds a level to the shared experience, as stated, the giver/sharer has also touched the object. Perhaps other elements lost are rarity and uniqueness. These elements add a great deal of value to an object, but in the digital realm, there is almost nothing which cannot be easily reproduced, either by copying it to many places or by replicating it through some digital tool. There is no risk of loss of something important with these digital objects. Almost all of us have some form of back up of our important information.

Of course, the information contained and shared is more important than how we choose to share it. Yet I do worry that, even though a piece of information shared is clearly important, we treat it with less reverence purely because of the sheer amount of information being shared with us at any one point in time. This may well be due to our lack of experience in dealing with this volume of information, and maybe it something we will become much better at over time.

However an interesting question and problem is raised: if we accept we are losing something, how do we create and share something of worth and value in a digital format? How can we impart and understand the time and effort expended to create that which is being shared? I’m not sure whether these questions are truly important, but they matter to me and I hope to some of you too.

 

If you have’t heard Mozilla identity labs has introduced a new way to login into sites called browserid. We have all become familiar with the “sign in with twitter” and “connect with Facebook” buttons on sites that enable us to have a centralised login to many of our favourite web services.

These centralised logins are very useful, but are ultimately controlled by a company. So into the breach steps Mozilla offering an openid type login service. Browserid is open source and you can choose to use mozilla as an authentication service or you can set up your own. I’m going to show you how to setup this service as a login and using Mozilla as the authenticator.

So assuming you have a login image with an Id attribute of “login” the following code should work in most modern browsers. I’m using jquery as the javascript framework.



$('document').ready(function (){

$('img.login').click(function(){
navigator.id.getVerifiedEmail(gotVerifiedEmail);
});

});
//this function is called in the above function
function gotVerifiedEmail(assertionObj){
If(assertionObj){
//Ajax to a login controller
$.ajax({
url:"/yourcontroller/youraction",
data:{assertion:assertionObj},
dataType:"json",
type:"post",
success:function(data,textStatus,jqXHR){
// do your thing
},
error:function(){
// something went wrong with ajax call
}
});
}else{
// something went wrong
}
}

So that’s the JavaScript part however we still need to verify the assertion with Mozilla. You can do this with JavaScript too. In the above code you would replace the call to your controller with
The following URL:
“https://browserid.org/verify?assertion=”+window.encodeURIComponent(assertionObj)+”&audience=”+window.encodeURIComponent(window.location.host);

In my controller class I do the following in a grails app:

def browserIdLogin ={

If(params.assertion){
def url = new URL(
"https://browserid.org/verify?assertion=${URLEncoder.encode(params.assertion)}&audience=
${URLEncoder.encode(request.getHeader('HOST'))}");

def jsonResponse= JSON.parse(url.text)

Println jsonResponse
}

}

// this will output something like [audience:localhost:8080, issuer:browserid.org:443, email:authedemail@email.com, status:okay, valid-until:1310908947530]

So you now you are dealing with an authentic user with authenic email address. Now you can do as you please. if this user already has an account you can load up their account details and set the session parameters etc or if they have no account you can send them to complete an account creation (if you need more details than the email address). After they complete this they can then sign in without needing to remember a password etc.

In php you could use the CURL library or open a socket etc or you could even just use


$jsonContent = file_get_contents("https://browserid.org/verify?assertion=".urlencode($_POST['assertion'])."&audience=".urlencode($_SERVER['HTTP_HOST']));

$jsonObj = json_decode($jsonContent);

echo $jsonObj->email;
?>

Anyway hope this is helpful. There is plenty of info on browserid and they also have example code.

© 2012 Craig Brookes Suffusion theme by Sayontan Sinha