Symfony4 Serviceクラスを使用してみる ～CURD編～ 【4】

## UPDATEを作成してみる	

UserServiceクラスに更新用メソッドを作成する

```php:src/Service/UserService.php
<?php

namespace App\Service;

use App\Service\CommonService;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class UserService
{
    private $manager;

    public function __construct(EntityManagerInterface $manager)
    {
        $this->manager = $manager;
    }

    (省略)    

    /**
     * ユーザーを更新するメソッド
     */
    public function updateUser(User $user, object $form, UserPasswordEncoderInterface $passwordEncoder)
    {
        // 現在の日付取得
        $common_serivce = new CommonService;
        $date = $common_serivce->getDate();

        $user = $form->getData();
        $password = $passwordEncoder->encodePassword($user, $user->getPassword());
        $user->setPassword($password);
        $user->setUpdatedAt($date);

        $this->manager->flush();
    }
}

```

コントローラークラスで呼び出す

```php:src/Controller/UserContoller.php
<?php

namespace App\Controller;

use App\Entity\User;
use App\Service\UserService;
use App\Form\UserType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class UserController extends AbstractController
{

    (省略)    

    /**
     * @Route("/user/update/{id}", name="user_update")
     */
    public function update(Request $request, User $user, UserService $user_service, UserPasswordEncoderInterface $passwordEncoder): Response
    {
        $form = $this->createForm(UserType::class, $user);
        $form->handleRequest($request);

        if ($request->getMethod() == 'POST') {
            // エラーチェック
            if ($user_service->checkUser($form)) {
                // ユーザーの作成
                $user_service->updateUser($user, $form, $passwordEncoder);
                
                // 成功したら一覧へ
                return $this->redirect('/user');
            }
        } else {
            return $this->render('user/form.html.twig', [
                'title' => 'ユーザー更新',
                'form' => $form->createView(),
            ]);
        }
    }
}

```



## DELETEを作成してみる	

UserServiceクラスに削除用メソッドを作成する

```php:src/Service/UserService.php
<?php

namespace App\Service;

use App\Service\CommonService;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class UserService
{
    private $manager;

    public function __construct(EntityManagerInterface $manager)
    {
        $this->manager = $manager;
    }

    (省略)    

    /**
     * ユーザーを削除するメソッド
     */
    public function deleteUser(User $user, object $form)
    {
        $user = $form->getData();

        $this->manager->remove($user);
        $this->manager->flush();
    }
}

```

コントローラークラスで呼び出す

```php:src/Controller/UserContoller.php
<?php

namespace App\Controller;

use App\Entity\User;
use App\Service\UserService;
use App\Form\UserType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class UserController extends AbstractController
{

    (省略)    

    /**
     * @Route("/user/delete/{id}", name="user_delete")
     */
    public function delete(Request $request, User $user, UserService $user_service): Response
    {
        $form = $this->createForm(UserType::class, $user);
        $form->handleRequest($request);

        if ($request->getMethod() == 'POST') {
            $user_service->deleteUser($user, $form);
            return $this->redirect('/user');
        } else {
            return $this->render('user/form.html.twig', [
                'title' => 'ユーザ削除',
                'form' => $form->createView(),
            ]);
        }
    }
}
```

### 以下目次

|タイトル|URL|
|----|----|
|タイトルページ|https://qiita.com/RyotaIhara/items/6159bbc38a729293fde0|
|READを作成してみる|https://qiita.com/RyotaIhara/items/ec5a5dff9bf00de87af7|
|CREATEを作成してみる|https://qiita.com/RyotaIhara/items/54942b2122d05ed561b1|
|UPDATEを作成してみる|https://qiita.com/RyotaIhara/items/f1fd3c17d6fa5ef78d34|
|DELETEを作成してみる|https://qiita.com/RyotaIhara/items/f1fd3c17d6fa5ef78d34|