-
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
userclass 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>_constructmethod 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>_constructmethod:... public function __construct(_OP $o) { // check data $o->_check(OP(array( 'id' => 'integer', 'email' =>$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 ofICallback), then that callback is executed, and the value of the property is passed as an argument. So in this case, our static methodcheckEmailwill be passed the value given foremail. Let’s change our test code and try this out:... // test
$oUser = new user(OP(array( 'id' => 1, 'email' => 'badexample.com',
)));
...
Now the e-mail address provided is invalid. When I run this code, I get the following error:
Error while processing input:
- Callback for
emailfailed.
Posted on April 27th, 2006
- Callback for