0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Symfony】セッションデータの保存について

Last updated at Posted at 2024-12-01

記事作成のきっかけ

自分への備忘録用として保存します。
Symfonyでのセッションの保存は、SessionInterfaceというライブラリを使って保存します。

完成イメージ

①入力欄にデータを入力して、Clickボタンを押下する。
symfony2.png

②セッションにデータが保存される。
symfony3.png

③空文字列を送信するとセッションが消える。
symfony4.png

こんな感じのアプリです。

ソフトウェアのバージョン

ソフトウェア バージョン
Symfony version5
PHP version8

セッションデータの保存方法

フロントのコードは下記のように記載します。

index.html.twig
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{{title}}</title>
</head>
<body>
    <h1>{{title}}</h1>
    <p>セッションデータ:{{ data }}</p>
    <form action='/hello' method='post'>
        Data:<input type='text' name='data'/>
    <input type='submit' value='Click'/>
    </form>
</body>
</html>

サーバサイドは、今回はMyDataクラスのGetter,Setterを使ってデータの授受をしたいので下記の手順で行います。
【手順】
①MyDataクラスのインスタンスを生成する。

 $data = new MyData();

②MyDataクラスのSetterにセッションデータを詰める。

$data->setData($request->get('data'));
HelloController.php
<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

class HelloController extends AbstractController
{
    /**
     * @Route("/hello",name="hello")
     */
    #[Route('/hello',name:'hello')]
    public function index(Request $request,SessionInterface $session)
    {
        //MyDataインスタンスを生成する
        $data = new MyData();
        
        $form = $this->createFormBuilder($data)
            ->add('data',TextType::class)
            ->add('save',SubmitType::class,['label'=>'Click'])
            ->getForm();
        
        //リクエストされた値をセットする
        $data->setData($request->get('data'));

        if($request->getMethod() == 'POST'){
            $form->handleRequest($request);

            $data = $form->getData();
            $obj = $form->getData();
            
            if($data == '!'){
                $session->remove('data');
            }else{
                $session->set('data',$data->getData());
            }
 
        }else{
            $msg = 'お名前をどうぞ';
        }
        
        // Twigテンプレートにフォームとメッセージを渡す
        return $this->render('hello/index.html.twig', [
            'title' => 'セッションデータを取得するアプリ',
            'data'=>$session->get('data'),
            'form'=>$form->createView(),
        ]);
  
    }

    #[Route('/notfound',name:'notfound')]
    public function notfound(Request $request)
    {
        $content = <<< EOM
        <html><head><title>ERROR</title></head>
        <body><h1>ERROR! 404</h1>
        </body></html>
        EOM;
        $response = new Response(
            $content,
            Response::HTTP_NOT_FOUND,
            array('content-type'=>'text/html')
        );
        return $response;
    }

    #[Route('/error',name:'error')]
    public function error(Request $request)
    {
        $content = <<< EOM
        <html><head><title>ERROR</title></head>
        <body><h1>ERROR! 500</h1>
        </body></html>
        EOM;

        $response = new Response(
            $content,
            Response::HTTP_INTERNAL_SERVER_ERROR,
            array('content-type'=>'text/html')
        );
        return $response;
    }

    #[Route('/other',name:'other')]
    public function other(Request $request)
    {
       $input = $request->request->get('input');
       $msg = 'こんにちは、'.$input.'さん。';
       return $this->render('hello/index.html.twig',[
        'title'=>'Hello',
        'message'=>$msg
       ]);
    }
       
}

class Person{
    protected $name;
    protected $age;
    protected $mail;

    public  function getName(){
        return $this->name;
    }

    public function setName($name){
        $this->name = $name;
        return $this;
    }

    public  function getAge(){
        return $this->age;
    }

    public function setAge($age){
        $this->age = $age;
        return $this;
    }

    public  function getMail(){
        return $this->mail;
    }

    public function setMail($mail){
        $this->mail = $mail;
        return $this;
    }
}

class MyData
{
    protected $data = '';
    public function getData()
    {
        return $this->data;
    }

    public function setData($data)
    {
        $this->data = $data;
    }
}

ざっくりですが、こんな感じでセッションを保存することができます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?