はじめに
テーブルに新規列を追加してControllerなどから利用したい。
ほぼこれのとおり。
EntityExtension~Proxy~DBアクセス
EntityExtension
dtb_productにmaker_name列を追加する予定
app/Customize/Entity/ProductTrait.php
<?php
namespace Customize\Entity;
use Doctrine\ORM\Mapping as ORM;
use Eccube\Annotation\EntityExtension;
/**
* @EntityExtension("Eccube\Entity\Product")
*/
trait ProductTrait
{
/**
* @ORM\Column(type="string", nullable=true)
*/
public $maker_name;
/**
* Set maker_name.
*
* @param string $maker_name
*
* @return Product
*/
public function setMakerName($maker_name)
{
$this->maker_name = $maker_name;
return $this;
}
/**
* Get maker_name.
*
* @return string
*/
public function getMakerName()
{
return $this->maker_name;
}
}
Proxy
Proxyクラス生成
php bin/console cache:clear --no-warmup
php bin/console eccube:generate:proxies
app/proxy/entity/Product.php
<?php
:
class Product extends \Eccube\Entity\AbstractEntity
{
use \Customize\Entity\ProductTrait;
:
DB Update
SQL確認
php bin/console doctrine:schema:update --dump-sql
SQL実行
php bin/console doctrine:schema:update --dump-sql --force
dtb_productにmake_name列が追加されているのを確認
Controllerよりアクセス
app/Customize/Controller/SamplePageController.php
namespace Customize\Controller;
use Eccube\Controller\AbstractController;
use Eccube\Entity\BaseInfo;
use Eccube\Entity\Product;
use Eccube\Repository\BaseInfoRepository;
use Eccube\Repository\ProductRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
class SamplePageController extends AbstractController
{
/** @var BaseInfo */
protected $baseInfo;
/** @var Product */
protected $productRepository;
/**
* SamplePageController constructor.
* @param BaseInfoRepository $baseInfoRepository
* @param ProductRepository $productRepository
*/
public function __construct(
BaseInfoRepository $baseInfoRepository,
ProductRepository $productRepository
)
{
$this->baseInfo = $baseInfoRepository->get();
$this->productRepository = $productRepository;
}
/**
* @Route("/sample/{id}", name="sample_index")
* @Template("Sample/index.twig")
*/
public function index($id)
{
// $product = $this->entityManager->getRepository('Eccube\Entity\Product')->find($id);
$product = $this->productRepository->find($id);
return [
'shop_name' => $this->baseInfo->getShopName(),
'maker_name' => $product->getMakerName(),
'product_name' => $product->getName(),
];
}
}
Template
app/template/default/Sample/index.twig
{% extends 'default_frame.twig' %}
{% block main %}
店舗名は"{{ shop_name }}"です。<br/>
メーカーは"{{ maker_name }}"です。<br/>
商品名は"{{ product_name }}"です。<br/>
{% endblock %}
ブラウザよりアクセス
/sample/1 で指定したmaker_nameが表示された。
まとめ
ほぼ「Entityのカスタマイズ Entity拡張 基本の拡張方法」のとおりでアクセス可能