Tuesday, November 30, 2010

Taking advantage of Exceptions in PHP

Another post about errors.

Exceptions are often overlooked because of the extra setup you need to do in order to create a good design even though I myself am not a guru of any object oriented design principles. Nevertheless, a programmer should take advantage of its capabilities.

 Here is a simple way of using an extended exception in php.

$franz = 'alien';
 try{
   if($franz != 'human'){
     throw new My_Extended_Exception('Error, you are not a human. Go back to your planet', 306);
   }
} catch (Exception $e) {
   echo $e->logError()->outputError();
}

The neat part with extending an exception is you can play with the class and do your own logging. As an example.

class My_Extended_Exception extends Exception
{
  protected $_errorMessage;

  public function __construct($message, $code)
  {
    parent::__construct($message, $code);
  }

  public function logError()
  {
    $this->_errorMessage = $this->message . ' code:' . $this->code . ' on line: ' . $this->getLine() . ' in file: ' . $this->getFile() . PHP_EOL;
     file_put_contents("errors.txt", $this->_errorMessage, FILE_APPEND | LOCK_EX);
    
     return $this;
  }
   
   // sends the error to the browser;
   public function outputError()
  {
    if($this->_errorMessage){
      return $this->_errorMessage;
    }
  }
}

A little about the code. By extending our exception we added a little ability to log our error messages then also output it to the browser. We basically automate the process and should have control on our errors.
Another big plus using an exception is the native methods of the error class. Here I used 2 which is getLine() and getFile(). Pretty self explanatory which will get the line number of the error and also the file where it came from. There are more of these methods in php.net documentation. I also passed the $message and $code argument to the parent class which is Exception in order to access the message and code property directly (eg: $this->message).

And thats it! hope it helped some.

Changing error messages in Zend Framework's Zend_Form

I was figuring a way to simply change an error message in Zend_Form specifically the Zend_Form_Element_EmailAddress because I dont like the default error message "is not a valid email address in the basic format local-part@hostname".

A simple way to do this is to use the setMessage() method of the Zend_Validate_EmailAddress. Here's my solution below:


$email = new Zend_Form_Element_Text('Email');
$email->setValidators(array(
                 array('EmailAddress', true),
               ));
$email->getValidator('EmailAddress')->setMessage('Ooops, %value% is wrong!!!', Zend_Validate_EmailAddress::INVALID_FORMAT);

In the code above, I have set the EmailAddress (Zend_Validate_EmailAddress) validator as a validator of my form's email element. In order to mess with the message, we need to retrieve the validator object by using the getValidator method of the Zend_Form_Element. From here you can access the set method setMessage and all you have to do is replace it with your new message, and target the message key which is Zend_Validate_EmailAddress::INVALID_FORMAT. Remember that setMessage overrides the default value of the INVALID constant.


Thats pretty much it!

Monday, November 29, 2010

PHP's array_map and trim

I often used the trim function of PHP to arrays. If you look at the documentation of trim in php.net or are familiar with PHP, you would know that it accepts string as its main argument.

To get to the point I always wanted to use trim and apply it to the elements of the array. One work around is to loop through each element and apply the trim to each element but an easier way is to use PHP's native function array_map(). An easy implementation from the code below.

$myArray = array('one', ' two ', ' three', 'four ');
$trimmedArray = array_map('trim', $myArray);
var_dump($trimmedArray);

That's it! One thing to note, if you have memory problems like me :) remembering syntax
you may get confused array_map with array_walk and or array_filter. Array_map() applies
the call back to each element of the array where as array_walk is most often used for walking over the array and just simply printing it. Although you can use array_walk also if you prefer.
Array_filters just filters the element using the call back and return the elements that satisfies you callback filter.

Hope it helps someone.

Friday, November 26, 2010

Installing Eclipse IDE in new system

I use eclipse a lot and this is like the 4th or so time i had to install a fresh copy to a new computer.
Problem is I keep having problems installing it since it always generate the Java Runtime Environment missing error and i cant remember how i did it the last time.

So for the last time, im documenting the installation process. I have a 64 bit Win 7 so if
you are using an x86 you may skip step 3-4.

1. Get a copy of eclipse. do the usual install.
2. On a fresh system you will get a runtime error telling you that you cant run Eclipse until you installed the Java JDK or JRE.
3 .Go to Sun/Oracle download page and if with luck, they might finally add the 64 bit JRE installer in their website. Problem is they dont have it there at the time of my installation so I have to scour the web for the installer.
I find it here: http://www.filehippo.com/download_jre_64/
There also one in CNET but its corrupted.
4. Install the JRE.
5. The easiest way to plug this in eclipse is by adding a shortcut to your desktop. Right click propertis -> target the add -vm "C:\Program Files\Java\jre6\bin\javaw.exe"
or depending on where you install the JRE

Thats it! Eclipse should work now!
What a pain huh?