記事作成背景
ORM マッパーを使ってテーブル情報を取得するための備忘録
検証環境
ソフトウェア | バージョン |
---|---|
PHP | 8.0* |
Symfony | 5.0* |
完成イメージ
こんな感じで、テーブルから取得した情報を画面に反映させてみます。
フロントページ(index.html.twg)の{{welcome_name}}の箇所にテーブル情報を入れてみます。
template/conference/index.html.twg
{% extends 'base.html.twig' %}
{% block title %}Hello ConferenceController!{% endblock %}
{% block body %}
<style>
.example-wrapper { margin: 1em auto; max-width: 800px; width: 95%; font: 18px/1.5 sans-serif; }
.example-wrapper code { background: #F5F5F5; padding: 2px 6px; }
</style>
<div class="example-wrapper">
<h1>Hello {{ controller_name }}! ✅</h1>
This friendly message is coming from:
<ul>
<li>Your controller at <code><a href="{{ 'C:/Users/pgrfr/Desktop/hellosymfony6/src/Controller/ConferenceController.php'|file_link(0) }}">src/Controller/ConferenceController.php</a></code></li>
<li>Your template at <code><a href="{{ 'C:/Users/pgrfr/Desktop/hellosymfony6/templates/conference/index.html.twig'|file_link(0) }}">templates/conference/index.html.twig</a></code></li>
</ul>
<div>
{{welcome_name}}
</div>
<div>
<a href="/conference/second">つぎへ</a>
</div>
</div>
{% endblock %}
サーバーとデータベースを接続するには、下記のI/Fライブラリが必要です。
Doctrine\ORM\EntityManagerInterface;
Productエンティティクラスも必要なので追加しておきましょう。
App\Entity\Product;
今回は、一意の情報を取得したいので、find()関数を使います。
手順は下記の通りになります。
【手順】
■private修飾子のメンバ変数:$entityManagerを追加する。
private $entityManager;
■Controllerクラスのコンストラクタを用意する。
public function __construct(EntityManagerInterface $entityManager){
$this->entityManager = $entityManager;
}
■entityManagerを使って一意の情報を取得する。
$memberlist = $this->entityManager->getRepository(Product::class)->find($id);
■EntityのGetterを使って変数に入れる。
$welcomename = $memberlist->getName();
■ビュー画面に返却
return $this->render('conference/index.html.twig', [
'controller_name' => $conferencedata,
'welcome_name'=>$welcomename
]);
上記の一連の流れをまとめた、コントローラクラスは下記の感じになります。
src/Controller/Conference.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\EntityManagerInterface;//追加
use App\Entity\Product; // Productエンティティの名前空間を正しく指定
class ConferenceController extends AbstractController
{
private $entityManager; //追加
//コンストラクタを追加
public function __construct(EntityManagerInterface $entityManager){
$this->entityManager = $entityManager;
}
#[Route('/conference', name: 'app_conference')]
public function index(): Response
{
$conferencedata = 'ConferenceController';
$id=1;
$memberlist = $this->entityManager->getRepository(Product::class)->find($id);
//dd($memberlist->getName());
$welcomename = $memberlist->getName();
return $this->render('conference/index.html.twig', [
'controller_name' => $conferencedata,
'welcome_name'=>$welcomename
]);
}
#[Route('/conference/second',name:'app_conference_second')]
public function secondPage():Response
{
$secondData = '遷移後のページ';
return $this->render('conference/second.html.twig', [
'second_page' => $secondData
]);
}
}
以上です。