Created
August 24, 2015 10:29
-
-
Save mCzolko/7bf5a0997e327304b30f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Duedil\Bundle\AppBundle\Command; | |
use Doctrine\ORM\EntityManager; | |
use Symfony\Component\Console\Command\Command; | |
use Symfony\Component\Console\Input\InputInterface; | |
use Symfony\Component\Console\Output\OutputInterface; | |
abstract class PersistALotOfEntitiesCommand extends Command | |
{ | |
/** @var EntityManager */ | |
private $entityManager; | |
/** @var int */ | |
private $persistedEntities = 0; | |
/** | |
* @param EntityManager $entityManager | |
* @param null $name | |
*/ | |
public function __construct(EntityManager $entityManager, $name = null) | |
{ | |
$this->entityManager = $entityManager; | |
parent::__construct($name); | |
} | |
/** | |
* @param InputInterface $input | |
* @param OutputInterface $output | |
*/ | |
protected function initialize(InputInterface $input, OutputInterface $output) | |
{ | |
parent::initialize($input, $output); | |
$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