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のレポジトリ・エンティティを利用してショップ設定を更新しています。
<?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
}
}
EC-CUBEに関するお問い合わせ
[重要]現在公式にセキュリティサポートが切れていないPHPは8.1以上、MySQLは8.0以上で、対応しているEC-CUBEバージョンは4.2以上です。古いEC-CUBEを使っている方は適切なタイミングでバージョンアップをご検討ください。
EC-CUBEゴールドパートナー