There is such a method:

protected function validateConfig($config) { $moduleId = $config['moduleId'] ?: null; $defaultVersion = $config['defaultVersion'] ?: null; $versions = $config['versions'] ?: null; $model = DynamicModel::validateData( compact('moduleId', 'defaultVersion', 'versions'), [ [['moduleId', 'defaultVersion', 'versions'], 'required'], [['moduleId', 'defaultVersion'], 'string'], [['moduleId'], 'string', 'max' => 255], [['versions'], function($attribute, $params) { if(!is_array($this->$attribute)){ $this->addError($attribute, Module::t('module-manager', 'Versions should be an array')); } }], ] ); return $model->hasErrors() ? false : true; } 

Here, using DynamicModel, I need to check the data from the $ config array.

  1. moduleId, defaultVersion and versions should be required.
  2. moduleId and defaultVersion is a string. Maximum 255 characters.
  3. versions must be an array.

I use an anonymous function for this purpose.

When I try to get $ this inside a function, I have a call to my class, which contains the validateConfig method.

I thought that DynamicModel creates a temporary model with moduleId, defaultVersion and versions properties. And I can refer to them.

How to write an anonymous function to validate this kind?

  • Well, it's logical. that $ this refers to the class, and where should it be? - Ninazu
  • To the model that DynamicModel dynamically creates. - LostDok

1 answer 1

Well then, as if not through a static do. An anonymous function has no idea about the existence of a model. And through statics you will not be able to work with it, since it has not yet been created, and you cannot transfer it to use

  $model = new DynamicModel(compact('moduleId', 'defaultVersion', 'versions')); $model->addRule(['versions'], function ($attribute, $params) use ($model) { if(!is_array($model->$attribute)){ $model->addError($attribute, 'Ахтунг'); } })->validate();