Symfonyの機能を使ったカスタマイズ
概要
EC-CUBEは、SymfonyやDoctrineをベースに開発されています。 そのため、SymfonyやDoctrineが提供している拡張機構を利用することができます。
ここでは、代表的な拡張機構とその実装方法を紹介します。
Symfony Event
Symfonyのイベントシステムを利用することができます。
hello worldを表示するイベントリスナーを作成する
app/Customize/EventListener配下ににHelloListener.phpを作成します。
<?php
namespace Customize\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class HelloListener implements EventSubscriberInterface
{
public function onResponse(FilterResponseEvent $event)
{
echo 'hello world';
}
public static function getSubscribedEvents()
{
return [
KernelEvents::RESPONSE => 'onResponse',
];
}
}
作成後、画面を表示(どのページでも表示されます)し、hello worldが表示されていれば成功です。
表示されない場合は、bin/console cache:clear --no-warmupでキャッシュを削除してください。
また、bin/console debug:event-dispatcherで登録されているイベントリスナーを確認できます。
イベントに関する詳細は以下を参照してください。
Command
bin/consoleから実行できるコンソールコマンドを作成することが出来ます。
hello worldを表示するコマンドを作成する
app/Customize/Command配下にHelloCommand.phpを作成します。
<?php
namespace Customize\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
class HelloCommand extends Command
{
// コマンド名
protected static $defaultName = 'acme:hello';
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
// hello worldを表示
$io->success('hello world');
}
}
$defaultNameはコマンド名を表します。$io->success('hello world')で、hello worldを表示します。
作成後、bin/consoleで実行することができます。
$ bin/console acme:hello
[OK] hello world
※ コマンドが認識されない場合は、bin/console cache:clear --no-warmupでキャッシュを削除してください。
Commandに関する詳細は以下を参照してください。
Doctrine Event
Doctrineのイベントシステムを利用することができます。
ショップ名にようこそを付与するイベントリスナーを作成する
app/Customize/Doctrine/EventSubscriber配下にHelloEventSubscriber.phpを作成します。
<?php
namespace Customize\Doctrine\EventSubscriber;
use Doctrine\Common\EventSubscriber;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use Eccube\Entity\BaseInfo;
class HelloEventSubscriber implements EventSubscriber
{
public function getSubscribedEvents()
{
return [Events::postLoad];
}
public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getObject();
if ($entity instanceof BaseInfo) {
$shopName = $entity->getShopName();
$shopName = 'ようこそ '.$shopName.' へ';
$entity->setShopName($shopName);
}
}
}
作成後、トップページを開き、ようこそ [ショップ名] へが表示されていれば成功です。
表示されない場合は、bin/console cache:clear --no-warmupでキャッシュを削除してください。
イベントに関する詳細は以下を参照してください。
※ Doctrine Event Listeners and Subscribersでは、services.yamlでの設定方法が記載されていますが、EC-CUBEはDoctrineのイベントリスナーをコンテナへ自動登録します。そのため、services.yamlでの設定は不要です。
SymfonyのBundleを利用する
TODO