Object Extensions for PHP — Runtime Object Extension for PHP

Download Now

Object Extensions for PHP is a extension for PHP that allows for runtime extension of PHP objects as well as other features like runtime callback definitions.

Callbacks 101: How to use callbacks to verify input

There are other ways to use the dynamic method callbacks provided by Object Extensions for PHP. For this demo, we’ll be expanding on our first two demos. Let’s start by adding a method to our user class to verify an e-mail address (really simple regex):

...

public static function checkEmail($sEmail) { // check the email with a regular expression return (boolean) preg_match( '/^[_a-zA-Z0-9\-\.]+*@[a-zA-Z0-9\-\.]+$/', $sEmail ); } ...

We’ve now created a function to check an e-mail address. Normally you would have to call it directly in your <em>_construct method to validate the e-mail address. However, we could do something else that would make things even simpler. Let’s go and change our </em>_construct method:

...
    public function __construct(_OP $o)
    {
        // check data
        $o->_check(OP(array(
            &apos;id&apos; => &apos;integer&apos;,
            &apos;email&apos; => $this->_callback()->checkEmail(),
        )));

        // extend
        $this->_extend($o);
    }
...

The feature I’ve used above is one that allows the _OP::_check() method to use a callback to verify input. This gives you more flexibility over the verification of data. If you specify a callback (or more specifically, an instance of ICallback), then that callback is executed, and the value of the property is passed as an argument. So in this case, our static method checkEmail will be passed the value given for email. Let’s change our test code and try this out:

...
// test
$oUser = new user(OP(array(
    &apos;id&apos; => 1,
    &apos;email&apos; => &apos;badexample.com&apos;,
)));

...

Now the e-mail address provided is invalid. When I run this code, I get the following error:


Error while processing input:

  • Callback for email failed.

Posted on April 27th, 2006

View all entries