'Symfony Form not releasing memory
I'm using Symfony Forms to validate data from an array in a loop.
For each item in the array, I create a form instance that trigger's a form submission.
After that, I check if the form is valid and then push the data to an array.
What I have noticed now is that for each run the memory usage increases by about 1 MB. And PHP seems not to clear the old form instances.
My code looks like this:
foreach ($dataToValidate as $item) {
$form = $this->formFactory->create($formType, $item, ['csrf_protection' => false, 'allow_extra_fields' => false]);
$form->submit($item);
if ($form->isSubmitted() && true === $form->isValid()) {
$validData[] = $form->getData();
}
}
I have tried things like this inside the foreach to clear the memory:
$form = null;
unset($form);
gc_collect_cycles();
But somehow the memory usage is getting bigger and bigger with every form-validation.
I have tested it with about 200 items in the $dataToValidate array.
Before the validation the memory usage (returned by memory_get_usage();) is at around 10 MB. After validating the 200 items it goes up to over 70 MB.
Edit
As it was asked in the comments: The form type's I'm using are pretty basic and look for example like this:

Solution 1:[1]
In this case, it seems to me that it would be more correct to use the Validator Component
Here is an example of how this can be implemented, only in your case, your array needs to be turned into an object of one or another entity:
$validator = Validation::createValidator();
$entity = new YouEntity();
$entity->setName('SOME_FIELD');
//...
$violations = $validator->validate($entity);
I specify rules mostly in entity in @Assert annotations
class User
{
/**
* @Assert\Length(min = 3)
* @Assert\NotBlank
*/
private $name;
/**
* @Assert\Email
* @Assert\NotBlank
*/
private $email;
/**
* @var string username
*
* @ORM\Column(name="username", type="string", length=50, unique=true, options={"comment":"username"})
* @Assert\Regex(pattern="/^[0-9A-Za-z-]+$/")
* @Assert\NotBlank()
* @Assert\Length(
* min = 4,
* max = 50)
*/
private $username;
//...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
