Archive

Archive for October, 2008

Writing dynamic classes with PHP

October 13, 2008 Leave a comment

I recently had the necessity to write a dynamic class (i.e. where methods, or properties of the class are determined during runtime) and in doing some research, stumbled on to this very helpful article :

Going dynamic with PHP

The author (Jack Herrington) goes to a lot of trouble explaining how the magic __get(), __set() and __call() methods work and how best to use them.

It does get a little bit complicated towards the end, but is a good example of a)why one should or need to use a dynamic class/object and b)how to implement it successfully within your application.

PHP wrapper class for Zend View

October 7, 2008 2 comments

I recently posted an article with an example of a Zend Session wrapper I’ve been using for some of my projects.

In that same vein I’ve created a simple wrapper for Zend View. I found this useful in instances where I didn’t need to use Zend Framework’s whole MVC implementation. Zend View is extremely helpful in creating a quick templating system for smaller projects or custom frameworks.

Once again I’ll be assuming the following:

First our view wrapper/abstraction class (view.php) :

<?php
/**
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to calisza@gmail.com so we can send you a copy immediately.
 *
 * @package    FlexiDev_View
 * @copyright  Copyright (c) 2007 - 2008,  Flexible Developments - Barry Roodt (https://calisza.wordpress.com)
 * @license    New BSD License
 */
 class View {
 	public $tmplVars;
 	public $view;

 	/**
 		Constructor
 	*/
 	public function __construct(){
		
 		$this->tmplVars = array();
 		// Instantiate our Zend View
		$this->view = new Zend_View();
		
		/**
		 * reset our basepath and scriptpaths, this is because we don't need the 'scripts', 'helpers' and 'filters' sub folders 
		 * relative to this script - of course you could change this as your needs require
		 */
		$this->view->setBasePath("./view");
		$this->view->setScriptPath("./view");
		
		// set and assign some global vars to our template
		// this is just an example - you can add more here
		$globals  = array("base_url" => $_SERVER["HTTP_HOST"]);
		$this->view->assign($globals);
 	}
 	/**
	 * Method to add to our template variable stack 
	 * @param string variable name
	 * @param mixed value
	 */ 
 	public function addTmplVar($key, $value){
 		/* If our stack doesn't already exist, create a new array */
 		if (!is_array($this->tmplVars)){
 			$this->tmplVars = array($key=>$value); 			
 		} else {
 			// Add to our variable stack
 			$this->tmplVars[$key] = $value;
 		}
 	}
 	/**
	 * Method to render the required view/template
	 * @param string template script name
	 * @param bool (optional) clear variable stack (default=true)
	 */ 
 	public function getTemplate($tmpl, $clearVars=true){
 		/* Add our variable stack to the template */
		$this->view->assign($this->tmplVars); 
		/* If required, clear our stack so that we can start with a fresh template on the next call */
		if ($clearVars)
			$this->tmplVars = "";
			
		/* Return the rendered template */
		return $this->view->render($tmpl);
	}
	
 }

?>

Next for some example usage (index.php) :

<?php
require_once("View.php");
$items = array ("Name" => "Barry", "Surname" => "Roodt", "Title" => "Mr");
$view = new View();
$view->addTmplVar("myitems", $items);
echo $view->getTemplate("template.phtml");
?>

And finally our view template (template.phtml) :

<div>Hi <?php echo $this->myitems["name"]; ?></div>
<div>Here is some information for you
<?php foreach($this->myitems as $key=>$val) : ?>
    <p><strong><?php echo $key; ?>: </strong><?php echo $val; ?></p>
<?php endforeach; ?>
</div>
<div>You can also use Zend View's default helpers like so : <?php echo $this->escape($this->myitems["name"]); ?></div>

You can also view an example of this class in action here.

As always, comments, critiques and corrections welcome.

Spam proof Contact Form with Zend Framework, ReCaptcha and Akismet / TypePad Antispam

October 3, 2008 7 comments

Update : Download Source code here
Update : View Working Demo

Over the last few weeks I’ve blogged on using the Zend Framework’s Akismet Service to “spam proof” your generic, run of the mill contact form.

Of course, services like Akismet and TypePad Antispam only come into play after the form has been submitted, a “cure” so to speak.

What we really need is some form of robust “prevention”. Stop the spam bots right at the door. There’s nothing more irritating than getting bombarded by 10k submissions every hour on the hour – even if they’re being filtered out by your Akismet / TypePad service.

Which brings us to the now common place CAPTCHA component. Designed to stop automated spam bots in their tracks, its a pretty effective method. Ordinarily, it’s not too difficult to implement a CAPTCHA component to your form, but ReCaptcha and the Zend Framework have now made it child’s play.

ReCaptcha is an online service providing a free CAPTCHA API for you to use. What’s also really nifty is that while your users fill in the CAPTCHA form, they’re also helping develop OCR software used to digitize books and manuscripts.

As an example I’ve gone and written a basic contact form, zipped it up and made it available here. Inside the zip file is all the code necessary for a very basic and hopefully spam proof contact form.

The following Zend Framework components were used :

  • Zend Loader
  • Zend Config
  • Zend View
  • Zend Service ReCaptcha
  • Zend Service Akismet
  • Zend Mail
  • Zend Validate
  • Zend Filter
  • Zend Registry

I’ve also included a simple wrapper for Zend View, since I didn’t feel that it was necessary to go the whole MVC route on this one.

The code used is pretty straightforward and easy to follow with as many comments thrown in there as I could stomach, but if you have any questions please feel free to leave a comment or send a mail.

Before you begin, you’ll need the following:

To use, unzip the file (it already contains the Zend Framework v1.6), edit the config.xml file and then simply customize the view scripts (view/form.php, view/success.php, view/mail.php).

Unfortunately I haven’t had much time to test the example thoroughly as it was written in a bit of a hurry (only had about an hour or so), so if you find or even fix any bugs please let me know and I’ll sort it out as soon as I get an opportunity to do so.

Update: I’ve amended 3 bugs thanks to comments from Mark. Affected files can be downloaded separately here, or you can download the full source again here. I’ve also created a working demo here.

  1. In view/form.php line 23 : “$this->TextArea” has been changed to “$this->Textarea”. TextArea works on my local host, but not when uploaded to my demo server.
  2. In view/form.php line 25-27 : Added a new paragraph containing “$this->captcha” to output the ReCaptcha element. This was not included in the zip file’s form.php for some inexplicable reason – my apologies
  3. In library/FlexiDev/Process.php line 122 : Logic error preventing ReCaptcha from verifying correctly. $recaptcha->verify(…) returns an object and not a boolean value – amended to $result = $recaptcha->verify(…); return $result->isValid();

One last note : the code is provided under the New BSD License, so have fun.