1

i have a validation class which needs improving. If I require some custom validation I need to specify a custom function. It works a bit like this:

  1. The controller tells the validation that a custom validation function is required.
  2. The controller runs the validation.
  3. --- Gets iffy here ---
  4. Validation class creates a new instance of the controller class....
  5. Validation class runs controller->custom_validation_function()
  6. Validation class returns true / false

Is there someway that I can alter this to do something like this?

$validation = new validation;
// Insert rules here.
$validation->function() = $this->function();

By doing this I could get rid of the step of creating an unneeded class instance.

user187291
  • 53,363
  • 19
  • 95
  • 127
ComputerUser
  • 4,828
  • 15
  • 58
  • 71

3 Answers3

6

You will want to use a Strategy Pattern. Have a Validator class for each validation you want to do and then instantiate this class in the consuming class as needed. Then delegate the validation to the validator instance.

Have a look at how Zend Framework does it for an idea.
Also see the example given in my answer to this related question:

Community
  • 1
  • 1
Gordon
  • 312,688
  • 75
  • 539
  • 559
1

PHP doesn't really support monkeypatching, but you could create either a subclass and use that as your $validation object (this is the way I would do it). Or you could figure out a way to use __call to do it: http://php.net/manual/en/language.oop5.overloading.php

SeanJA
  • 10,234
  • 5
  • 32
  • 42
1

Checkout the delegates example at phpclasses.com.

$processruns->add(function() { echo "hello"; });
$processruns->add(function() { echo "world"; }); 

Also, this discussion might help.

Community
  • 1
  • 1
KMån
  • 9,896
  • 2
  • 31
  • 41