Skip to content

Instantly share code, notes, and snippets.

@mCzolko
Created August 23, 2015 00:25
Show Gist options
  • Save mCzolko/9bc6f272b38c2fb6c125 to your computer and use it in GitHub Desktop.
Save mCzolko/9bc6f272b38c2fb6c125 to your computer and use it in GitHub Desktop.
Base Command object for saving huge amout of entities to prevent memory leaks.
<?php
namespace Acme\DemoBundle\Command;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
abstract class PersistLotEntitiesCommand extends ContainerAwareCommand
{
/** @var EntityManager */
private $entityManager;
/** @var int */
private $persistedEntities = 0;
/**
* @param InputInterface $input
* @param OutputInterface $output
*/
protected function initialize(InputInterface $input, OutputInterface $output)
{
parent::initialize($input, $output);
$this->entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
$this->entityManager->getConnection()->getConfiguration()->setSQLLogger(null); // Save memory
gc_enable(); // Save memory
}
/**
* @param $entity
*/
protected function persistEntity($entity)
{
$this->entityManager->persist($entity);
if ($this->persistedEntities > $this->getPersistThreshold()) {
$this->flush();
}
++$this->persistedEntities;
}
/**
* Entity manager flush and clear unused objects.
*/
private function flush()
{
$this->entityManager->flush();
$this->entityManager->clear();
gc_collect_cycles(); // Save memory
$this->persistedEntities = 0;
}
/**
* How many entities should be persisted before flushing.
*
* @return int
*/
public function getPersistThreshold()
{
return 99;
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return int
* @throws \Exception
*/
public function run(InputInterface $input, OutputInterface $output)
{
$statusCode = parent::run($input, $output);
$this->flush();
return $statusCode;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment