EC-CUBE3(Silex)ではApplication::getInstance()により$appオブジェクトを取得し、そこから$app[‘orm.em’]としてエンティティマネージャを呼び出していました。
それではEC-CUBE4(Symfony3)ではどのようにエンティティやレポジトリをマイグレーションで使用するのでしょうか?
結論から言うとマイグレーションファイルにContainerAwareInterfaceを実装することでcontainerを使用することができるようになり、レポジトリクラスのオブジェクトを取得できます。
実装方法
ContainerAwareInterfaceをimplementsし、実装したsetContainerメソッド内でコンテナを保持します。
postUpメソッド内でcontainerやentity managerを利用してレポジトリ・エンティティを呼び出します。
マイグレーションで送料無料条件を設定する例
次の例では送料無料条件(金額)を10,800円に設定するEC-CUBE4のマイグレーションです。
BaseInfoのレポジトリ・エンティティを利用してショップ設定を更新しています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<?php declare(strict_types=1); namespace DoctrineMigrations; use Doctrine\DBAL\Schema\Schema; use Doctrine\Migrations\AbstractMigration; use Doctrine\ORM\EntityManager; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20190106043954 extends AbstractMigration implements ContainerAwareInterface { private $container; /** * @var EntityManager */ private $em; public function setContainer(ContainerInterface $container = null) { $this->container = $container; $this->em = $this->container->get('doctrine.orm.entity_manager');; } public function up(Schema $schema) : void { } public function postUp(Schema $schema) { $repository = $this->em->getRepository('Eccube\Entity\BaseInfo'); $BaseInfo = $repository->get(); $BaseInfo->setDeliveryFreeAmount(10800); $this->em->flush($BaseInfo); } public function down(Schema $schema) : void { // this down() migration is auto-generated, please modify it to your needs } } |