Jump to content

Is this a good use for anonymous functions?


NotionCommotion

Recommended Posts

I've always had an issue needing to write and maintain script to validate both client side and sever side so a while back I wrote a validation class whose primary purpose was:

  • Accept in its constructor a JSON string which is mostly identical to the jQuery validation option except it also included a "sanitize" property.  For instance: {"rules": {"account": {"minlength": 6}}, "messages": {"account": {"minlength": "Six numbers are required"}, "sanitize":{"account":int}}.
  • Provide the correct jQuery validation option so a form can be validated client side.
  • Sanitize the form data server side.
  • Validate the form data server side.

I recently looked at the code and it is a train wreck.  I used a single class and had a bunch of protected functions where some would validate per a given rule and return the message upon error and others would sanitize.  For non-typical rules required by the specific application, I would extend the class and add them.  Some of these added rules required other resources such as an entities primary key, a PDO connection, etc.

While inheritance worked fine to add simple rules, it did not do so for the rules which needed other resources.  Also, even though I used "final" on my base class methods, I never liked this single class of many methods as I couldn't use the same name for a given rule and sanitize method (i.e. would rather use digit and digit instead of digit and int).

I am thinking of changing it to something like the following.  While this is definitely better, I question whether I should be using traditional classes to define my standard and custom rules.  Any recommendations?  Thanks

class Validator
{
    protected $options,
    $rules=[
        "digit"=>function($value, $prop, $name){
            return /*validate and return error string or null*/;
        },
        "minlength"=>"ect, etc"    
    ];

    public function __construct(string $json, \Closure ...$customRules=[]) {
        $this->options=json_decode($json);
        $this->rules=array_merge($this->rules, $customRules);
    }
}
class Application
{
    public function someMethod() {
        $pdo=$this->pdo;
        $applicationCustomRules=[
            'someCustomRule'=>function($value, $prop, $name) use ($pdo) {
                return /*validate and return error string or null*/;
            }
        ];
        $validator=new Validator($json, ...$applicationCustomRules);

        //Which can be used such as:
        $jQueryOptions=$validator->getJQueryOptions();
        $validator->validate($data);
        $validator->validateProperty('account', $account);
    }
}

 

Link to comment
Share on other sites

I might use regular methods, like

class Application
{

	public function someMethod() {
		$applicationCustomRules = [
			'someCustomRule' => [$this, 'customRuleValidation']
		];
		// ...
	}

	public function customRuleValidation($value, $prop, $name) {
		// ...
	}

}

Same for that one in Validator.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.