# Symfony面接質問集: 2026年トップ25 > 最も多く尋ねられるSymfony面接質問25選。アーキテクチャ、Doctrine ORM、サービス、セキュリティ、フォーム、テストを詳細な回答とコード例とともに解説。 - Published: 2026-02-02 - Updated: 2026-04-27 - Author: SharpSkill - Tags: symfony, php, interview, doctrine, technical interview - Reading time: 24 min --- Symfonyの面接では、リファレンスとなるプロフェッショナルなPHPフレームワークの習熟度、コンポーネント指向アーキテクチャの理解、Doctrine ORMの理解、堅牢でスケーラブルなアプリケーションを構築する能力が問われます。本ガイドでは、Symfonyの基礎から高度な本番運用パターンまで、最も多く尋ねられる25の質問を取り上げます。 > **面接のヒント** > > リクルーターはSymfonyの哲学を理解している候補者を高く評価します。サービスによる疎結合、明示的な設定、PSR標準への準拠です。フレームワークのアーキテクチャ上の選択を説明できることが差をつけます。 ## Symfonyの基礎 ### 質問1: Symfonyにおけるリクエストのライフサイクルを説明してください Symfonyのリクエストのライフサイクルは、HTTPカーネルを経由し、各ステップで拡張可能とするためにイベントシステムを利用します。これを理解することは、デバッグやアプリケーション挙動のカスタマイズに不可欠です。 ```php // public/index.php // すべてのHTTPリクエストのエントリポイント use App\Kernel; require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; // Symfony Runtimeがbootstrapを処理します return function (array $context) { return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']); }; ``` ```php // src/Kernel.php // Kernelがリクエスト処理を統括します namespace App; use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; use Symfony\Component\HttpKernel\Kernel as BaseKernel; class Kernel extends BaseKernel { use MicroKernelTrait; // Kernelはbundleを読み込み、コンテナを設定します // ライフサイクルの主要なイベント: // 1. kernel.request - ルーティング前 // 2. kernel.controller - コントローラ解決後 // 3. kernel.view - コントローラがResponseを返さない場合 // 4. kernel.response - レスポンス送信前 // 5. kernel.terminate - 送信後(非同期タスク) } ``` 完全なサイクル: `index.php` → Runtime → Kernel → HttpKernel → EventDispatcher (kernel.request) → Router → Controller → EventDispatcher (kernel.response) → Response。各ステップはEvent Subscriberで横取りできます。 ### 質問2: SymfonyにおけるService ContainerとDependency Injectionとは何ですか? Service Container(あるいはDIC, Dependency Injection Container)はSymfonyの中核です。アプリケーションのすべてのサービスのインスタンス化、設定、注入を管理します。 ```php // src/Service/PaymentService.php // 自動的に依存が注入されるサービス namespace App\Service; use App\Repository\OrderRepository; use Psr\Log\LoggerInterface; use Symfony\Contracts\HttpClient\HttpClientInterface; class PaymentService { public function __construct( private readonly HttpClientInterface $stripeClient, // 設定済みHTTPクライアント private readonly OrderRepository $orderRepository, // Doctrineリポジトリ private readonly LoggerInterface $logger, // PSR-3ロガー private readonly string $stripeApiKey, // 注入されたパラメータ ) {} public function processPayment(int $orderId, float $amount): bool { $order = $this->orderRepository->find($orderId); try { $response = $this->stripeClient->request('POST', '/charges', [ 'body' => [ 'amount' => $amount * 100, 'currency' => 'eur', 'source' => $order->getPaymentToken(), ], ]); $order->markAsPaid($response->toArray()['id']); $this->orderRepository->save($order, true); return true; } catch (\Exception $e) { $this->logger->error('Payment failed', [ 'order' => $orderId, 'error' => $e->getMessage(), ]); return false; } } } ``` ```yaml # config/services.yaml # サービスの設定 services: _defaults: autowire: true # type-hintによる自動注入 autoconfigure: true # タグの自動設定 App\: resource: '../src/' exclude: - '../src/DependencyInjection/' - '../src/Entity/' - '../src/Kernel.php' # パラメータを伴う明示的な設定 App\Service\PaymentService: arguments: $stripeClient: '@stripe.client' $stripeApiKey: '%env(STRIPE_API_KEY)%' ``` Autowiringはtype-hintによって依存関係を自動的に解決します。スカラーパラメータは明示的な設定が必要です。 ### 質問3: BundleとSymfonyコンポーネントの違いは何ですか? Bundleは再利用可能なパッケージで、機能をSymfonyアプリケーションに統合します。コンポーネントはSymfonyなしでも利用できる独立したPHPライブラリです。 ```php // src/MyBundle/MyBundle.php // カスタムBundleの構造 namespace App\MyBundle; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; use Symfony\Component\HttpKernel\Bundle\AbstractBundle; class MyBundle extends AbstractBundle { // bundleの設定を読み込みます public function loadExtension( array $config, ContainerConfigurator $container, ContainerBuilder $builder ): void { // bundleのサービスを読み込みます $container->import('../config/services.yaml'); // 条件付きの設定 if ($config['feature_enabled']) { $container->services() ->set('my_bundle.feature_service', FeatureService::class) ->autowire(); } } // bundleのデフォルト設定 public function configure(DefinitionConfigurator $definition): void { $definition->rootNode() ->children() ->booleanNode('feature_enabled')->defaultTrue()->end() ->scalarNode('api_key')->isRequired()->end() ->end(); } } ``` ```php // Symfonyなしでコンポーネントを使う // コンポーネントは独立したPHPライブラリです use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; // 任意のPHPプロジェクトで利用可能 $request = Request::createFromGlobals(); $response = new Response('Hello World', 200); $response->send(); ``` Bundleは設定、サービス、リソースをまとめて提供します。コンポーネントはどこでも再利用できる低レベルのツールです。 ### 質問4: SymfonyのEvent Subscriberはどのように動作しますか? Event Subscriberは、フレームワークやアプリケーションのイベントに反応し、ビジネスロジックをメインコードから切り離すことを可能にします。 ```php // src/EventSubscriber/ApiExceptionSubscriber.php namespace App\EventSubscriber; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpKernel\Event\ExceptionEvent; use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; use Symfony\Component\HttpKernel\KernelEvents; class ApiExceptionSubscriber implements EventSubscriberInterface { // 購読するイベントとその優先度を宣言します public static function getSubscribedEvents(): array { return [ // 高い優先度(他より先に実行) KernelEvents::EXCEPTION => ['onKernelException', 100], KernelEvents::RESPONSE => ['onKernelResponse', 0], ]; } public function onKernelException(ExceptionEvent $event): void { $exception = $event->getThrowable(); $request = $event->getRequest(); // APIリクエストのみを扱います if (!str_starts_with($request->getPathInfo(), '/api')) { return; } $statusCode = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : 500; $response = new JsonResponse([ 'error' => true, 'message' => $exception->getMessage(), 'code' => $statusCode, ], $statusCode); // レスポンスを我々のJSONで置き換えます $event->setResponse($response); } public function onKernelResponse(\Symfony\Component\HttpKernel\Event\ResponseEvent $event): void { // カスタムヘッダを追加します $event->getResponse()->headers->set('X-Api-Version', '1.0'); } } ``` Event Subscriberはautoconfigureのおかげで自動検出されます。優先度は実行順序を決定します(高いほど先に実行)。 ## Doctrine ORM ### 質問5: Doctrineの関連とその違いを説明してください Doctrineはエンティティ間の関連をモデル化するために複数の関連型を提供します。各タイプはクエリやパフォーマンスに影響します。 ```php // src/Entity/User.php namespace App\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; #[ORM\Entity(repositoryClass: UserRepository::class)] class User { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] private ?int $id = null; // OneToOne関連: ユーザは1つのプロファイルを持ちます #[ORM\OneToOne(mappedBy: 'user', cascade: ['persist', 'remove'])] private ?Profile $profile = null; // OneToMany関連: ユーザは複数の記事を持ちます #[ORM\OneToMany(mappedBy: 'author', targetEntity: Article::class, orphanRemoval: true)] private Collection $articles; // ManyToMany関連: 複数のユーザは複数のロールを持ちます #[ORM\ManyToMany(targetEntity: Role::class, inversedBy: 'users')] #[ORM\JoinTable(name: 'user_roles')] private Collection $roles; public function __construct() { // コレクションの初期化は必須です $this->articles = new ArrayCollection(); $this->roles = new ArrayCollection(); } public function addArticle(Article $article): static { if (!$this->articles->contains($article)) { $this->articles->add($article); $article->setAuthor($this); // 双方向同期 } return $this; } public function removeArticle(Article $article): static { if ($this->articles->removeElement($article)) { if ($article->getAuthor() === $this) { $article->setAuthor(null); } } return $this; } } ``` ```php // src/Entity/Article.php #[ORM\Entity(repositoryClass: ArticleRepository::class)] class Article { // ManyToOne関連: 複数の記事は1人の著者に属します #[ORM\ManyToOne(inversedBy: 'articles')] #[ORM\JoinColumn(nullable: false)] private ?User $author = null; // pivotエンティティを介した属性付きManyToMany #[ORM\OneToMany(mappedBy: 'article', targetEntity: ArticleTag::class)] private Collection $articleTags; } ``` 双方向の関連は手動の同期が必要です。"owning"側(JoinColumn/JoinTableを持つ側)が永続化を制御します。 ### 質問6: N+1問題とは何で、Doctrineでどのように解決しますか? N+1問題は、メインクエリが関連を読み込むためにN個の追加クエリを発行してしまうときに起きます。Symfonyアプリケーションで最も一般的な遅延の原因です。 ```php // src/Repository/ArticleRepository.php namespace App\Repository; use App\Entity\Article; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Persistence\ManagerRegistry; class ArticleRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, Article::class); } // 悪い例: 著者にアクセスするとN+1クエリ public function findAllBad(): array { return $this->findAll(); // + 著者を読むため記事ごとに1クエリ } // 良い例: eager fetchでJOIN public function findAllWithAuthor(): array { return $this->createQueryBuilder('a') ->addSelect('u') // 著者もSELECT ->leftJoin('a.author', 'u') // 関連でJOIN ->orderBy('a.publishedAt', 'DESC') ->getQuery() ->getResult(); } // 良い例: 複数関連向けの複数JOIN public function findAllWithDetails(): array { return $this->createQueryBuilder('a') ->addSelect('u', 'c', 't') // すべての関連をSELECT ->leftJoin('a.author', 'u') ->leftJoin('a.comments', 'c') ->leftJoin('a.tags', 't') ->where('a.status = :status') ->setParameter('status', 'published') ->orderBy('a.publishedAt', 'DESC') ->getQuery() ->getResult(); } // 良い例: 大規模リスト向けのバッチ読み込み public function findAllOptimized(): array { $query = $this->createQueryBuilder('a') ->getQuery(); // 関連を100件単位でバッチ読み込み $query->setFetchMode(Article::class, 'author', ClassMetadata::FETCH_BATCH); return $query->getResult(); } } ``` DoctrineパネルのSymfony ProfilerはN+1問題の検出に役立ちます。クエリ数はWeb Debug Toolbarに表示されます。 ### 質問7: Query ExtensionとDoctrineフィルタはどのように作りますか? Query ExtensionとDoctrineフィルタは、すべてのクエリに条件を自動適用できる仕組みです。マルチテナンシーやソフトデリートに最適です。 ```php // src/Doctrine/Extension/CurrentUserExtension.php // ユーザで自動的にフィルタするためのAPI Platform拡張 namespace App\Doctrine\Extension; use ApiPlatform\Doctrine\Orm\Extension\QueryCollectionExtensionInterface; use ApiPlatform\Doctrine\Orm\Extension\QueryItemExtensionInterface; use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface; use ApiPlatform\Metadata\Operation; use App\Entity\Article; use Doctrine\ORM\QueryBuilder; use Symfony\Bundle\SecurityBundle\Security; final class CurrentUserExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface { public function __construct( private readonly Security $security, ) {} public function applyToCollection( QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, array $context = [] ): void { $this->addWhere($queryBuilder, $resourceClass); } public function applyToItem( QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, ?Operation $operation = null, array $context = [] ): void { $this->addWhere($queryBuilder, $resourceClass); } private function addWhere(QueryBuilder $queryBuilder, string $resourceClass): void { // Articleにのみ適用 if ($resourceClass !== Article::class) { return; } // adminはすべて閲覧可能 if ($this->security->isGranted('ROLE_ADMIN')) { return; } $user = $this->security->getUser(); $rootAlias = $queryBuilder->getRootAliases()[0]; // 著者による自動フィルタ $queryBuilder ->andWhere(sprintf('%s.author = :current_user', $rootAlias)) ->setParameter('current_user', $user); } } ``` ```php // src/Doctrine/Filter/SoftDeleteFilter.php // 削除済み要素を除外するグローバルなDoctrineフィルタ namespace App\Doctrine\Filter; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Query\Filter\SQLFilter; class SoftDeleteFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, string $targetTableAlias): string { // エンティティにdeletedAtフィールドがあるかをチェック if (!$targetEntity->hasField('deletedAt')) { return ''; } return sprintf('%s.deleted_at IS NULL', $targetTableAlias); } } ``` ```yaml # config/packages/doctrine.yaml doctrine: orm: filters: soft_delete: class: App\Doctrine\Filter\SoftDeleteFilter enabled: true ``` フィルタはSQLレベル、ExtensionはQueryBuilderレベルで適用されます。一時的な無効化は`$em->getFilters()->disable('soft_delete')`で行えます。 ## Symfonyのセキュリティ ### 質問8: Symfonyのセキュリティシステムはどのように動作しますか? SymfonyのSecurityコンポーネントは、認証(誰がユーザか)と認可(何ができるか)を、拡張可能なアーキテクチャで管理します。 ```yaml # config/packages/security.yaml security: password_hashers: Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto' providers: app_user_provider: entity: class: App\Entity\User property: email firewalls: dev: pattern: ^/(_(profiler|wdt)|css|images|js)/ security: false api: pattern: ^/api stateless: true jwt: ~ # Lexik JWT Bundle main: lazy: true provider: app_user_provider form_login: login_path: app_login check_path: app_login enable_csrf: true logout: path: app_logout remember_me: secret: '%kernel.secret%' lifetime: 604800 access_control: - { path: ^/api/login, roles: PUBLIC_ACCESS } - { path: ^/api, roles: ROLE_USER } - { path: ^/admin, roles: ROLE_ADMIN } ``` ```php // src/Security/CustomAuthenticator.php // 特定ロジックのためのカスタムauthenticator namespace App\Security; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator; use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge; use Symfony\Component\Security\Http\Authenticator\Passport\Passport; use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport; class ApiKeyAuthenticator extends AbstractAuthenticator { public function supports(Request $request): ?bool { // このauthenticatorはX-API-KEYを持つリクエストのみ扱う return $request->headers->has('X-API-KEY'); } public function authenticate(Request $request): Passport { $apiKey = $request->headers->get('X-API-KEY'); if (null === $apiKey) { throw new AuthenticationException('No API key provided'); } // UserBadgeはidentifierでユーザを読み込む return new SelfValidatingPassport( new UserBadge($apiKey, function (string $apiKey) { // APIキーからユーザを読み込むロジック return $this->userRepository->findByApiKey($apiKey); }) ); } public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response { // null = 通常通りリクエストを継続 return null; } public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response { return new JsonResponse([ 'error' => $exception->getMessage(), ], Response::HTTP_UNAUTHORIZED); } } ``` セキュリティアーキテクチャはFirewall(設定)、Authenticator(認証)、Voter(認可)で構成されます。 ### 質問9: 細粒度の認可のためにVoterをどう実装しますか? Voterは複雑かつ再利用可能な認可ロジックを記述でき、ビジネスルールをコントローラのコードから切り離します。 ```php // src/Security/Voter/ArticleVoter.php namespace App\Security\Voter; use App\Entity\Article; use App\Entity\User; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\Voter\Voter; class ArticleVoter extends Voter { public const VIEW = 'ARTICLE_VIEW'; public const EDIT = 'ARTICLE_EDIT'; public const DELETE = 'ARTICLE_DELETE'; protected function supports(string $attribute, mixed $subject): bool { // このvoterはArticleと指定属性のみ扱う return in_array($attribute, [self::VIEW, self::EDIT, self::DELETE]) && $subject instanceof Article; } protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool { $user = $token->getUser(); $article = $subject; // 公開済み記事は誰でも閲覧可能 if ($attribute === self::VIEW && $article->isPublished()) { return true; } // 他のアクションは認証済みユーザが必要 if (!$user instanceof User) { return false; } return match ($attribute) { self::VIEW => $this->canView($article, $user), self::EDIT => $this->canEdit($article, $user), self::DELETE => $this->canDelete($article, $user), default => false, }; } private function canView(Article $article, User $user): bool { // 下書きは著者かadminのみ閲覧可能 return $article->getAuthor() === $user || in_array('ROLE_ADMIN', $user->getRoles()); } private function canEdit(Article $article, User $user): bool { // 著者だけが編集可能 return $article->getAuthor() === $user; } private function canDelete(Article $article, User $user): bool { // 著者またはadminが削除可能 return $article->getAuthor() === $user || in_array('ROLE_ADMIN', $user->getRoles()); } } ``` ```php // src/Controller/ArticleController.php // コントローラでのVoterの利用 use Symfony\Component\Security\Http\Attribute\IsGranted; class ArticleController extends AbstractController { #[Route('/articles/{id}/edit', name: 'article_edit')] #[IsGranted(ArticleVoter::EDIT, subject: 'article')] public function edit(Article $article): Response { // 認可は自動的に検証されます // voterが拒否すれば403 } // プログラム的な代替手段 #[Route('/articles/{id}', name: 'article_show')] public function show(Article $article): Response { $this->denyAccessUnlessGranted(ArticleVoter::VIEW, $article); // または条件付きで if (!$this->isGranted(ArticleVoter::EDIT, $article)) { // 編集ボタンを隠す } } } ``` ```twig {# Twig内 #} {% if is_granted('ARTICLE_EDIT', article) %} 編集 {% endif %} ``` Voterは自動検出され、`isGranted()`の呼び出し時に参照されます。デフォルト戦略では、少なくとも1つのVoterが賛成票を投じればアクセスを許可します。 ### 質問10: SymfonyでJWTを使ってAPIをどう保護しますか? JWT(JSON Web Token)認証はステートレスAPI向けの標準的な解です。Symfonyでは通常、LexikJWTAuthenticationBundleを使用します。 ```yaml # config/packages/lexik_jwt_authentication.yaml lexik_jwt_authentication: secret_key: '%env(resolve:JWT_SECRET_KEY)%' public_key: '%env(resolve:JWT_PUBLIC_KEY)%' pass_phrase: '%env(JWT_PASSPHRASE)%' token_ttl: 3600 # 1時間 ``` ```php // src/Controller/Api/AuthController.php namespace App\Controller\Api; use App\Entity\User; use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; use Symfony\Component\Routing\Attribute\Route; #[Route('/api')] class AuthController extends AbstractController { #[Route('/login', name: 'api_login', methods: ['POST'])] public function login( Request $request, UserPasswordHasherInterface $passwordHasher, JWTTokenManagerInterface $jwtManager, ): JsonResponse { $data = json_decode($request->getContent(), true); $user = $this->userRepository->findOneBy(['email' => $data['email']]); if (!$user || !$passwordHasher->isPasswordValid($user, $data['password'])) { return new JsonResponse(['error' => 'Invalid credentials'], 401); } // JWTトークンを生成 $token = $jwtManager->create($user); return new JsonResponse([ 'token' => $token, 'user' => [ 'id' => $user->getId(), 'email' => $user->getEmail(), 'roles' => $user->getRoles(), ], ]); } #[Route('/refresh-token', name: 'api_refresh_token', methods: ['POST'])] public function refreshToken(): JsonResponse { // bundleが設定されていれば自動的に処理されます // refresh tokenから新しいtokenを返します } } ``` ```php // src/EventListener/JWTCreatedListener.php // JWTペイロードのカスタマイズ namespace App\EventListener; use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent; class JWTCreatedListener { public function onJWTCreated(JWTCreatedEvent $event): void { $user = $event->getUser(); $payload = $event->getData(); // tokenにカスタムデータを追加 $payload['user_id'] = $user->getId(); $payload['email'] = $user->getEmail(); $payload['permissions'] = $user->getPermissions(); $event->setData($payload); } } ``` JWT tokenは`Authorization: Bearer `ヘッダで送信します。bundleが署名と有効期限を自動で検証します。 ## Symfonyのフォーム ### 質問11: バリデーション付きの高度なフォームはどう作成しますか? SymfonyのFormコンポーネントは、HTMLフォームを生成し、送信処理を行い、constraintでデータを検証します。 ```php // src/Form/ArticleType.php namespace App\Form; use App\Entity\Article; use App\Entity\Category; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\DateTimeType; use Symfony\Component\Form\Extension\Core\Type\FileType; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Validator\Constraints as Assert; class ArticleType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options): void { $builder ->add('title', TextType::class, [ 'label' => '記事タイトル', 'attr' => ['placeholder' => 'タイトルを入力...'], 'constraints' => [ new Assert\NotBlank(message: 'タイトルは必須です'), new Assert\Length( min: 10, max: 255, minMessage: 'タイトルは{{ limit }}文字以上必要です', ), ], ]) ->add('content', TextareaType::class, [ 'label' => '本文', 'constraints' => [ new Assert\NotBlank(), new Assert\Length(min: 100), ], ]) ->add('category', EntityType::class, [ 'class' => Category::class, 'choice_label' => 'name', 'placeholder' => 'カテゴリを選択', 'query_builder' => function ($repo) { return $repo->createQueryBuilder('c') ->where('c.active = true') ->orderBy('c.name', 'ASC'); }, ]) ->add('coverImage', FileType::class, [ 'label' => 'カバー画像', 'mapped' => false, // エンティティに紐付けない 'required' => false, 'constraints' => [ new Assert\Image( maxSize: '5M', mimeTypes: ['image/jpeg', 'image/png', 'image/webp'], mimeTypesMessage: '対応していない画像形式です', ), ], ]) ->add('publishedAt', DateTimeType::class, [ 'widget' => 'single_text', 'required' => false, 'label' => '公開日', ]); // フォームを動的に変更するためのEvent listener $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { $article = $event->getData(); $form = $event->getForm(); // 編集時のみ追加するフィールド if ($article && $article->getId()) { $form->add('slug', TextType::class, [ 'disabled' => true, 'help' => 'slugは変更できません', ]); } }); } public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'data_class' => Article::class, 'validation_groups' => ['Default', 'article_creation'], ]); } } ``` ```php // src/Controller/ArticleController.php #[Route('/articles/new', name: 'article_new')] public function new(Request $request, SluggerInterface $slugger): Response { $article = new Article(); $form = $this->createForm(ArticleType::class, $article); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { // ファイルアップロードの処理 $coverImage = $form->get('coverImage')->getData(); if ($coverImage) { $filename = $slugger->slug($article->getTitle()).'-'.uniqid().'.'.$coverImage->guessExtension(); $coverImage->move($this->getParameter('covers_directory'), $filename); $article->setCoverImageFilename($filename); } $this->entityManager->persist($article); $this->entityManager->flush(); $this->addFlash('success', '記事を作成しました!'); return $this->redirectToRoute('article_show', ['id' => $article->getId()]); } return $this->render('article/new.html.twig', [ 'form' => $form, ]); } ``` FormEvents(`PRE_SET_DATA`、`POST_SUBMIT`など)はコンテキストに応じたフィールドの動的変更を可能にします。 ### 質問12: constraintを使ったカスタムバリデーションをどう実装しますか? Symfonyでは複雑なビジネスルール向けに、独自のバリデーション制約を作成できます。 ```php // src/Validator/UniqueEmail.php // カスタム制約 namespace App\Validator; use Symfony\Component\Validator\Constraint; #[\Attribute(\Attribute::TARGET_PROPERTY)] class UniqueEmail extends Constraint { public string $message = 'メール "{{ value }}" は既に使用されています。'; public ?int $excludeId = null; // 更新時に現在のユーザを除外するため } ``` ```php // src/Validator/UniqueEmailValidator.php // 制約に紐づくvalidator namespace App\Validator; use App\Repository\UserRepository; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Exception\UnexpectedTypeException; class UniqueEmailValidator extends ConstraintValidator { public function __construct( private readonly UserRepository $userRepository, ) {} public function validate(mixed $value, Constraint $constraint): void { if (!$constraint instanceof UniqueEmail) { throw new UnexpectedTypeException($constraint, UniqueEmail::class); } if (null === $value || '' === $value) { return; // 空はNotBlankに任せる } $existingUser = $this->userRepository->findOneBy(['email' => $value]); // 同メールのユーザが存在し、かつ // 現在のユーザではない場合(更新時) if ($existingUser && $existingUser->getId() !== $constraint->excludeId) { $this->context->buildViolation($constraint->message) ->setParameter('{{ value }}', $value) ->addViolation(); } } } ``` ```php // src/Entity/User.php // エンティティでの制約利用 use App\Validator as AppAssert; use Symfony\Component\Validator\Constraints as Assert; class User { #[Assert\NotBlank] #[Assert\Email] #[AppAssert\UniqueEmail] private ?string $email = null; #[Assert\NotBlank] #[Assert\Length(min: 8)] #[Assert\Regex( pattern: '/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/', message: 'パスワードは大文字・小文字・数字を含める必要があります' )] private ?string $plainPassword = null; } ``` ```php // 複数フィールド検証用のクラスレベル制約 // src/Validator/PasswordMatch.php #[\Attribute(\Attribute::TARGET_CLASS)] class PasswordMatch extends Constraint { public string $message = 'パスワードが一致しません。'; public function getTargets(): string { return self::CLASS_CONSTRAINT; } } ``` カスタム制約は自動検出されます。`Validator`サフィックスはvalidatorで必須です。 ## Messengerと非同期通信 ### 質問13: Messengerで非同期処理をどう実装しますか? Symfony Messengerはメッセージをキューへ送信し、非同期処理を行うことでアプリケーションの応答性を高めます。 ```php // src/Message/SendWelcomeEmail.php // メッセージ(データを保持するDTO) namespace App\Message; final class SendWelcomeEmail { public function __construct( public readonly int $userId, public readonly string $locale = 'en', ) {} } ``` ```php // src/MessageHandler/SendWelcomeEmailHandler.php // メッセージを処理するハンドラ namespace App\MessageHandler; use App\Message\SendWelcomeEmail; use App\Repository\UserRepository; use Symfony\Bridge\Twig\Mime\TemplatedEmail; use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Messenger\Attribute\AsMessageHandler; #[AsMessageHandler] final class SendWelcomeEmailHandler { public function __construct( private readonly UserRepository $userRepository, private readonly MailerInterface $mailer, ) {} public function __invoke(SendWelcomeEmail $message): void { $user = $this->userRepository->find($message->userId); if (!$user) { return; // 途中でユーザが削除された } $email = (new TemplatedEmail()) ->to($user->getEmail()) ->subject('プラットフォームへようこそ!') ->htmlTemplate('emails/welcome.html.twig') ->context([ 'user' => $user, 'locale' => $message->locale, ]); $this->mailer->send($email); } } ``` ```yaml # config/packages/messenger.yaml framework: messenger: failure_transport: failed transports: async: dsn: '%env(MESSENGER_TRANSPORT_DSN)%' retry_strategy: max_retries: 3 delay: 1000 multiplier: 2 failed: dsn: 'doctrine://default?queue_name=failed' routing: # メッセージをasyncトランスポートにルーティング App\Message\SendWelcomeEmail: async App\Message\ProcessImage: async App\Message\GenerateReport: async ``` ```php // src/Controller/RegistrationController.php // メッセージのディスパッチ use Symfony\Component\Messenger\MessageBusInterface; class RegistrationController extends AbstractController { #[Route('/register', name: 'app_register', methods: ['POST'])] public function register( Request $request, MessageBusInterface $bus, ): Response { // ... ユーザ作成 // 非同期ディスパッチ - メールはバックグラウンドで送信 $bus->dispatch(new SendWelcomeEmail( userId: $user->getId(), locale: $request->getLocale(), )); // ユーザへ即座に応答 return $this->redirectToRoute('app_login'); } } ``` ワーカーは`php bin/console messenger:consume async -vv`で起動します。本番ではSupervisorでワーカーを常駐させます。 ### 質問14: Messengerでエラーとリトライをどう扱いますか? Messengerは堅牢な失敗対処メカニズムを提供します: 自動リトライ、デッドレターキュー、失敗メッセージの手動処理です。 ```php // src/MessageHandler/ProcessPaymentHandler.php namespace App\MessageHandler; use App\Exception\PaymentFailedException; use App\Exception\PaymentRetryableException; use App\Message\ProcessPayment; use Symfony\Component\Messenger\Attribute\AsMessageHandler; use Symfony\Component\Messenger\Exception\RecoverableMessageHandlingException; use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException; #[AsMessageHandler] final class ProcessPaymentHandler { public function __invoke(ProcessPayment $message): void { try { $this->paymentGateway->process($message->orderId); } catch (PaymentRetryableException $e) { // 一時的なエラー(timeout、rate limit) → リトライ throw new RecoverableMessageHandlingException( $e->getMessage(), previous: $e ); } catch (PaymentFailedException $e) { // 恒久的なエラー(無効なカード) → リトライしない throw new UnrecoverableMessageHandlingException( $e->getMessage(), previous: $e ); } } } ``` ```php // src/Message/ProcessPayment.php // メッセージ単位のリトライ設定 namespace App\Message; use Symfony\Component\Messenger\Stamp\DelayStamp; final class ProcessPayment { public function __construct( public readonly int $orderId, public readonly int $attempt = 1, ) {} // 試行回数に応じたリトライ遅延 public function getRetryDelay(): int { return match ($this->attempt) { 1 => 5000, // 5秒 2 => 30000, // 30秒 3 => 300000, // 5分 default => 600000, }; } } ``` ```bash # 失敗メッセージの管理コマンド php bin/console messenger:failed:show # 失敗メッセージを一覧表示 php bin/console messenger:failed:retry # すべて再試行 php bin/console messenger:failed:retry 123 # 特定メッセージを再試行 php bin/console messenger:failed:remove 123 # メッセージを削除 ``` リトライ戦略と"failed"トランスポートにより、メッセージが失われない仕組みを保証できます。メッセージは分析して手動で再試行できます。 ## Symfonyでのテスト ### 質問15: Symfonyではテストをどう構成しますか? SymfonyはPHPUnitに加え、各層を試験するための専用ヘルパーを提供します: ユニット、ファンクショナル、インテグレーションです。 ```php // tests/Unit/Service/PriceCalculatorTest.php // ユニットテスト: 単独クラスを検証 namespace App\Tests\Unit\Service; use App\Service\PriceCalculator; use PHPUnit\Framework\TestCase; class PriceCalculatorTest extends TestCase { private PriceCalculator $calculator; protected function setUp(): void { $this->calculator = new PriceCalculator(); } public function testCalculateTotalWithoutDiscount(): void { $total = $this->calculator->calculateTotal(100.00, 0); $this->assertEquals(100.00, $total); } public function testCalculateTotalWithPercentageDiscount(): void { $total = $this->calculator->calculateTotal(100.00, 20); $this->assertEquals(80.00, $total); } /** * @dataProvider discountProvider */ public function testCalculateTotalWithVariousDiscounts( float $price, int $discount, float $expected ): void { $total = $this->calculator->calculateTotal($price, $discount); $this->assertEquals($expected, $total); } public static function discountProvider(): array { return [ 'no discount' => [100.00, 0, 100.00], '10% discount' => [100.00, 10, 90.00], '50% discount' => [200.00, 50, 100.00], 'max discount' => [100.00, 100, 0.00], ]; } } ``` ```php // tests/Functional/Controller/ArticleControllerTest.php // ファンクショナルテスト: HTTP経由でコントローラを検証 namespace App\Tests\Functional\Controller; use App\Entity\Article; use App\Entity\User; use Doctrine\ORM\EntityManagerInterface; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class ArticleControllerTest extends WebTestCase { private $client; private EntityManagerInterface $entityManager; protected function setUp(): void { $this->client = static::createClient(); $this->entityManager = static::getContainer()->get(EntityManagerInterface::class); } public function testListArticlesReturnsOk(): void { $this->client->request('GET', '/articles'); $this->assertResponseIsSuccessful(); $this->assertSelectorExists('h1'); } public function testCreateArticleRequiresAuthentication(): void { $this->client->request('GET', '/articles/new'); $this->assertResponseRedirects('/login'); } public function testAuthenticatedUserCanCreateArticle(): void { // 認証 $user = $this->createUser(); $this->client->loginUser($user); // フォームへアクセス $crawler = $this->client->request('GET', '/articles/new'); $this->assertResponseIsSuccessful(); // フォーム送信 $form = $crawler->selectButton('作成')->form([ 'article[title]' => 'Test Article Title', 'article[content]' => 'これは十分な文字数を持つテスト記事の本文です。', ]); $this->client->submit($form); // 検証 $this->assertResponseRedirects(); $this->client->followRedirect(); $this->assertSelectorTextContains('h1', 'Test Article Title'); // データベースで確認 $article = $this->entityManager->getRepository(Article::class) ->findOneBy(['title' => 'Test Article Title']); $this->assertNotNull($article); } private function createUser(): User { $user = new User(); $user->setEmail('test@example.com'); $user->setPassword('$2y$13$hashedpassword'); $this->entityManager->persist($user); $this->entityManager->flush(); return $user; } protected function tearDown(): void { // テスト用DBをクリーンアップ $this->entityManager->getConnection()->executeStatement('DELETE FROM article'); $this->entityManager->getConnection()->executeStatement('DELETE FROM user'); parent::tearDown(); } } ``` ユニットテスト(kernelなし)、ファンクショナルテスト(kernelあり)、インテグレーションテスト(実サービス利用)を分けるのが望ましいです。 ### 質問16: fixtureとDatabaseResetterはどう使いますか? Fixtureは現実的なテストデータでDBを満たします。DoctrineTestBundleコンポーネントはテスト間のリセットを容易にします。 ```php // src/DataFixtures/ArticleFixtures.php namespace App\DataFixtures; use App\Entity\Article; use App\Entity\User; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Persistence\ObjectManager; class ArticleFixtures extends Fixture implements DependentFixtureInterface { public function load(ObjectManager $manager): void { for ($i = 1; $i <= 20; $i++) { $article = new Article(); $article->setTitle("Test Article Number $i"); $article->setSlug("test-article-$i"); $article->setContent("記事番号$iの詳細な本文..."); $article->setStatus($i <= 15 ? 'published' : 'draft'); $article->setPublishedAt($i <= 15 ? new \DateTimeImmutable("-$i days") : null); // UserFixturesが作成したユーザを参照 $article->setAuthor($this->getReference('user-'.($i % 3), User::class)); $manager->persist($article); // 他fixture用にreferenceを作成 $this->addReference("article-$i", $article); } $manager->flush(); } public function getDependencies(): array { // UserFixturesはArticleFixtures前にロード必要 return [ UserFixtures::class, ]; } } ``` ```php // src/DataFixtures/UserFixtures.php namespace App\DataFixtures; use App\Entity\User; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Bundle\FixturesBundle\FixtureGroupInterface; use Doctrine\Persistence\ObjectManager; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; class UserFixtures extends Fixture implements FixtureGroupInterface { public function __construct( private readonly UserPasswordHasherInterface $passwordHasher, ) {} public function load(ObjectManager $manager): void { $users = [ ['email' => 'admin@example.com', 'roles' => ['ROLE_ADMIN'], 'ref' => 'user-0'], ['email' => 'author@example.com', 'roles' => ['ROLE_AUTHOR'], 'ref' => 'user-1'], ['email' => 'user@example.com', 'roles' => ['ROLE_USER'], 'ref' => 'user-2'], ]; foreach ($users as $userData) { $user = new User(); $user->setEmail($userData['email']); $user->setRoles($userData['roles']); $user->setPassword($this->passwordHasher->hashPassword($user, 'password123')); $manager->persist($user); $this->addReference($userData['ref'], $user); } $manager->flush(); } public static function getGroups(): array { return ['test', 'dev']; } } ``` ```php // tests/Functional/ArticleControllerTest.php // 自動リセットのためのDAMADoctrineTestBundle namespace App\Tests\Functional; use App\Entity\Article; use Doctrine\ORM\EntityManagerInterface; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class ArticleControllerTest extends WebTestCase { use \DAMA\DoctrineTestBundle\Doctrine\DBAL\StaticDriver; public function testPublishedArticlesCount(): void { $client = static::createClient(); $em = static::getContainer()->get(EntityManagerInterface::class); $count = $em->getRepository(Article::class) ->count(['status' => 'published']); $this->assertEquals(15, $count); // fixturesに従う } } ``` ```bash # fixtureのロード php bin/console doctrine:fixtures:load php bin/console doctrine:fixtures:load --group=test php bin/console doctrine:fixtures:load --env=test ``` DAMADoctrineTestBundleは各テストをロールバックされるトランザクションで包み、テスト間でのfixture再ロードを不要にします。 ## アーキテクチャと高度なパターン ### 質問17: SymfonyでCQRSをどう実装しますか? CQRS(Command Query Responsibility Segregation)は読み込みと書き込みを分離し、それぞれを独立して最適化できるようにします。 ```php // src/Message/Command/CreateArticleCommand.php // Command: 変更の意図を表現 namespace App\Message\Command; final class CreateArticleCommand { public function __construct( public readonly string $title, public readonly string $content, public readonly int $authorId, public readonly array $tagIds = [], ) {} } ``` ```php // src/MessageHandler/Command/CreateArticleCommandHandler.php // CommandHandler: 変更を実行 namespace App\MessageHandler\Command; use App\Entity\Article; use App\Message\Command\CreateArticleCommand; use App\Repository\TagRepository; use App\Repository\UserRepository; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Messenger\Attribute\AsMessageHandler; use Symfony\Component\String\Slugger\SluggerInterface; #[AsMessageHandler] final class CreateArticleCommandHandler { public function __construct( private readonly EntityManagerInterface $entityManager, private readonly UserRepository $userRepository, private readonly TagRepository $tagRepository, private readonly SluggerInterface $slugger, ) {} public function __invoke(CreateArticleCommand $command): Article { $author = $this->userRepository->find($command->authorId) ?? throw new \InvalidArgumentException('Author not found'); $article = new Article(); $article->setTitle($command->title); $article->setSlug($this->slugger->slug($command->title)->lower()); $article->setContent($command->content); $article->setAuthor($author); foreach ($command->tagIds as $tagId) { $tag = $this->tagRepository->find($tagId); if ($tag) { $article->addTag($tag); } } $this->entityManager->persist($article); $this->entityManager->flush(); return $article; } } ``` ```php // src/Message/Query/GetArticleBySlugQuery.php // Query: 読み取り要求を表現 namespace App\Message\Query; final class GetArticleBySlugQuery { public function __construct( public readonly string $slug, public readonly bool $withComments = false, ) {} } ``` ```php // src/MessageHandler/Query/GetArticleBySlugQueryHandler.php // QueryHandler: データ取得(最適化されたread modelも使用可) namespace App\MessageHandler\Query; use App\DTO\ArticleDTO; use App\Message\Query\GetArticleBySlugQuery; use App\Repository\ArticleRepository; use Symfony\Component\Messenger\Attribute\AsMessageHandler; #[AsMessageHandler] final class GetArticleBySlugQueryHandler { public function __construct( private readonly ArticleRepository $repository, ) {} public function __invoke(GetArticleBySlugQuery $query): ?ArticleDTO { $qb = $this->repository->createQueryBuilder('a') ->select('a', 'u') ->leftJoin('a.author', 'u') ->where('a.slug = :slug') ->setParameter('slug', $query->slug); if ($query->withComments) { $qb->addSelect('c') ->leftJoin('a.comments', 'c'); } $article = $qb->getQuery()->getOneOrNullResult(); return $article ? ArticleDTO::fromEntity($article) : null; } } ``` ```php // src/Controller/ArticleController.php // CommandバスとQueryバスの利用 use Symfony\Component\Messenger\MessageBusInterface; use Symfony\Component\Messenger\Stamp\HandledStamp; class ArticleController extends AbstractController { public function __construct( private readonly MessageBusInterface $commandBus, private readonly MessageBusInterface $queryBus, ) {} #[Route('/articles', methods: ['POST'])] public function create(Request $request): Response { $data = json_decode($request->getContent(), true); $envelope = $this->commandBus->dispatch(new CreateArticleCommand( title: $data['title'], content: $data['content'], authorId: $this->getUser()->getId(), )); $article = $envelope->last(HandledStamp::class)->getResult(); return $this->json($article, 201); } #[Route('/articles/{slug}', methods: ['GET'])] public function show(string $slug): Response { $envelope = $this->queryBus->dispatch(new GetArticleBySlugQuery( slug: $slug, withComments: true, )); $article = $envelope->last(HandledStamp::class)->getResult(); return $this->json($article); } } ``` CQRSは読み取り(キャッシュ、プロジェクション)と書き込み(検証、イベント)を別々に最適化できます。 ### 質問18: SymfonyでRepository Patternを正しく実装するには? Repository PatternはSymfonyではDoctrineを通じて既に存在しますが、インターフェースとビジネスメソッドを加えて拡張できます。 ```php // src/Repository/Contract/ArticleRepositoryInterface.php // 疎結合とテスト容易性のためのインターフェース namespace App\Repository\Contract; use App\Entity\Article; use Doctrine\Common\Collections\Collection; interface ArticleRepositoryInterface { public function find(int $id): ?Article; public function findBySlug(string $slug): ?Article; public function findPublished(int $limit = 20, int $offset = 0): array; public function findByAuthor(int $authorId): array; public function save(Article $article, bool $flush = false): void; public function remove(Article $article, bool $flush = false): void; } ``` ```php // src/Repository/ArticleRepository.php // repositoryのDoctrine実装 namespace App\Repository; use App\Entity\Article; use App\Repository\Contract\ArticleRepositoryInterface; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Persistence\ManagerRegistry; class ArticleRepository extends ServiceEntityRepository implements ArticleRepositoryInterface { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, Article::class); } public function findBySlug(string $slug): ?Article { return $this->createQueryBuilder('a') ->addSelect('u', 't') ->leftJoin('a.author', 'u') ->leftJoin('a.tags', 't') ->where('a.slug = :slug') ->setParameter('slug', $slug) ->getQuery() ->getOneOrNullResult(); } public function findPublished(int $limit = 20, int $offset = 0): array { return $this->createQueryBuilder('a') ->addSelect('u') ->leftJoin('a.author', 'u') ->where('a.status = :status') ->setParameter('status', 'published') ->orderBy('a.publishedAt', 'DESC') ->setMaxResults($limit) ->setFirstResult($offset) ->getQuery() ->getResult(); } public function findByAuthor(int $authorId): array { return $this->createQueryBuilder('a') ->where('a.author = :authorId') ->setParameter('authorId', $authorId) ->orderBy('a.createdAt', 'DESC') ->getQuery() ->getResult(); } public function save(Article $article, bool $flush = false): void { $this->getEntityManager()->persist($article); if ($flush) { $this->getEntityManager()->flush(); } } public function remove(Article $article, bool $flush = false): void { $this->getEntityManager()->remove($article); if ($flush) { $this->getEntityManager()->flush(); } } // 複雑なクエリメソッド public function findPopularByCategory(int $categoryId, int $limit = 5): array { return $this->createQueryBuilder('a') ->addSelect('u') ->leftJoin('a.author', 'u') ->where('a.category = :categoryId') ->andWhere('a.status = :status') ->setParameter('categoryId', $categoryId) ->setParameter('status', 'published') ->orderBy('a.viewCount', 'DESC') ->setMaxResults($limit) ->getQuery() ->getResult(); } } ``` ```yaml # config/services.yaml # インターフェースと実装の紐づけ services: App\Repository\Contract\ArticleRepositoryInterface: alias: App\Repository\ArticleRepository ``` インターフェースによりテスト用実装(InMemoryArticleRepository)を作成したり、ビジネスコードを変えずにデータソースを切り替えたりできます。 ### 質問19: Symfonyで設定と環境はどう管理しますか? Symfonyは環境変数、シークレット、環境ごとのYAMLファイルをサポートする柔軟な設定システムを採用します。 ```yaml # config/packages/framework.yaml # 既定の設定 framework: secret: '%env(APP_SECRET)%' http_method_override: false handle_all_throwables: true session: handler_id: null cookie_secure: auto cookie_samesite: lax storage_factory_id: session.storage.factory.native php_errors: log: true ``` ```yaml # config/packages/prod/framework.yaml # 本番向けの上書き framework: session: handler_id: '%env(REDIS_URL)%' cookie_secure: true when@prod: framework: router: strict_requirements: null ``` ```php // config/secrets/prod/prod.decrypt.private.php // 機密シークレットの管理(暗号化) // php bin/console secrets:set DATABASE_URL --env=prod // php bin/console secrets:list --reveal --env=prod ``` ```php // src/DependencyInjection/Configuration.php // bundle向けカスタム設定 namespace App\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder(): TreeBuilder { $treeBuilder = new TreeBuilder('my_app'); $treeBuilder->getRootNode() ->children() ->scalarNode('api_key') ->isRequired() ->cannotBeEmpty() ->end() ->integerNode('cache_ttl') ->defaultValue(3600) ->min(0) ->end() ->arrayNode('features') ->addDefaultsIfNotSet() ->children() ->booleanNode('dark_mode')->defaultTrue()->end() ->booleanNode('beta_features')->defaultFalse()->end() ->end() ->end() ->end(); return $treeBuilder; } } ``` ```php // src/Service/ConfigurableService.php // 設定の注入 namespace App\Service; use Symfony\Component\DependencyInjection\Attribute\Autowire; class ConfigurableService { public function __construct( #[Autowire('%env(API_KEY)%')] private readonly string $apiKey, #[Autowire('%kernel.project_dir%')] private readonly string $projectDir, #[Autowire('%my_app.cache_ttl%')] private readonly int $cacheTtl, ) {} } ``` Symfonyのシークレットは暗号化されバージョン管理されます。実行時の値には`%env(...)%`、静的な値にはパラメータを使います。 ## パフォーマンスと本番運用 ### 質問20: Symfonyアプリケーションのパフォーマンスをどう最適化しますか? 最適化はopcache、設定、アプリケーションキャッシュ、Doctrineクエリといった複数のレベルにまたがります。 ```php // config/packages/prod/doctrine.yaml # 本番向けに最適化されたDoctrine設定 doctrine: orm: auto_generate_proxy_classes: false metadata_cache_driver: type: pool pool: doctrine.system_cache_pool query_cache_driver: type: pool pool: doctrine.system_cache_pool result_cache_driver: type: pool pool: doctrine.result_cache_pool ``` ```yaml # config/packages/cache.yaml # Redis利用のキャッシュ設定 framework: cache: app: cache.adapter.redis system: cache.adapter.system pools: doctrine.result_cache_pool: adapter: cache.adapter.redis default_lifetime: 3600 doctrine.system_cache_pool: adapter: cache.adapter.system services: Redis: class: Redis calls: - connect: - '%env(REDIS_HOST)%' - '%env(int:REDIS_PORT)%' Symfony\Component\Cache\Adapter\RedisAdapter: arguments: - '@Redis' ``` ```php // src/Repository/ArticleRepository.php // Doctrine result cacheの利用 public function findPopularCached(): array { return $this->createQueryBuilder('a') ->addSelect('u') ->leftJoin('a.author', 'u') ->where('a.status = :status') ->setParameter('status', 'published') ->orderBy('a.viewCount', 'DESC') ->setMaxResults(10) ->getQuery() ->enableResultCache(3600, 'popular_articles') // 1時間キャッシュ ->getResult(); } ``` ```bash # 本番向け最適化コマンド php bin/console cache:clear --env=prod php bin/console cache:warmup --env=prod php bin/console doctrine:cache:clear-metadata --env=prod php bin/console doctrine:cache:clear-query --env=prod # Doctrineプロキシを生成 php bin/console doctrine:proxy:create-proxy-classes # 最適化されたautoloaderをコンパイル composer install --no-dev --optimize-autoloader --classmap-authoritative ``` OPcacheは本番環境で最適設定で有効にすべきです。warmupはコンテナとルータのキャッシュを生成します。 ### 質問21: Symfonyでのログとモニタリングの設定方法は? 構造化ログと適切な監視は本番環境での問題診断に不可欠です。 ```yaml # config/packages/prod/monolog.yaml monolog: handlers: main: type: fingers_crossed action_level: error handler: nested excluded_http_codes: [404, 405] buffer_size: 50 nested: type: stream path: '%kernel.logs_dir%/%kernel.environment%.log' level: debug formatter: monolog.formatter.json console: type: console process_psr_3_messages: false channels: ['!event', '!doctrine'] slack: type: slack token: '%env(SLACK_TOKEN)%' channel: '#alerts' level: critical bot_name: 'SymfonyBot' ``` ```php // src/Service/PaymentService.php // コンテキスト付きの構造化ログ namespace App\Service; use Psr\Log\LoggerInterface; class PaymentService { public function __construct( private readonly LoggerInterface $logger, ) {} public function processPayment(Order $order): bool { $this->logger->info('Payment processing started', [ 'order_id' => $order->getId(), 'amount' => $order->getTotal(), 'currency' => $order->getCurrency(), 'user_id' => $order->getUser()->getId(), ]); try { $result = $this->gateway->charge($order); $this->logger->info('Payment successful', [ 'order_id' => $order->getId(), 'transaction_id' => $result->getTransactionId(), ]); return true; } catch (\Exception $e) { $this->logger->error('Payment failed', [ 'order_id' => $order->getId(), 'error' => $e->getMessage(), 'exception' => $e, ]); return false; } } } ``` ```php // src/EventSubscriber/RequestLoggerSubscriber.php // HTTPリクエストのログ namespace App\EventSubscriber; use Psr\Log\LoggerInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\TerminateEvent; use Symfony\Component\HttpKernel\KernelEvents; class RequestLoggerSubscriber implements EventSubscriberInterface { public function __construct( private readonly LoggerInterface $logger, ) {} public static function getSubscribedEvents(): array { return [ KernelEvents::TERMINATE => 'onKernelTerminate', ]; } public function onKernelTerminate(TerminateEvent $event): void { $request = $event->getRequest(); $response = $event->getResponse(); $this->logger->info('Request completed', [ 'method' => $request->getMethod(), 'uri' => $request->getRequestUri(), 'status' => $response->getStatusCode(), 'duration_ms' => round((microtime(true) - $request->server->get('REQUEST_TIME_FLOAT')) * 1000), 'memory_mb' => round(memory_get_peak_usage(true) / 1024 / 1024, 2), ]); } } ``` JSON形式は監視ツール(ELK、Datadog)による取り込みを容易にします。チャンネルでログ種別ごとに絞り込みできます。 ### 質問22: Symfonyアプリケーションを本番にどうデプロイしますか? 堅牢なSymfonyのデプロイは、ビルド準備、安全なマイグレーション、原子的な切り替えを組み合わせます。 ```bash #!/bin/bash # deploy.sh - デプロイスクリプト set -e RELEASE_DIR="/var/www/releases/$(date +%Y%m%d%H%M%S)" SHARED_DIR="/var/www/shared" CURRENT_LINK="/var/www/current" echo "リリースディレクトリを作成中..." mkdir -p $RELEASE_DIR echo "リポジトリをクローン中..." git clone --depth 1 --branch main git@github.com:org/repo.git $RELEASE_DIR echo "依存関係をインストール中..." cd $RELEASE_DIR composer install --no-dev --optimize-autoloader --classmap-authoritative echo "共有ファイルをリンク中..." ln -sf $SHARED_DIR/.env.local $RELEASE_DIR/.env.local ln -sf $SHARED_DIR/var/log $RELEASE_DIR/var/log ln -sf $SHARED_DIR/public/uploads $RELEASE_DIR/public/uploads echo "マイグレーションを実行中..." php bin/console doctrine:migrations:migrate --no-interaction --allow-no-migration echo "キャッシュをウォームアップ中..." php bin/console cache:clear --env=prod --no-debug php bin/console cache:warmup --env=prod --no-debug echo "権限を設定中..." chown -R www-data:www-data $RELEASE_DIR echo "新しいリリースに切り替え中..." ln -sfn $RELEASE_DIR $CURRENT_LINK echo "PHP-FPMを再起動中..." sudo systemctl reload php8.3-fpm echo "Messengerワーカーを再起動中..." php bin/console messenger:stop-workers echo "古いリリースをクリーンアップ中..." ls -dt /var/www/releases/*/ | tail -n +6 | xargs rm -rf echo "デプロイ完了!" ``` ```yaml # .github/workflows/deploy.yml # GitHub Actionsを利用したCI/CDデプロイ name: Deploy on: push: branches: [main] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: '8.3' extensions: intl, pdo_pgsql, redis - name: Install dependencies run: composer install --no-dev --optimize-autoloader - name: Run tests run: php bin/phpunit - name: Deploy to production uses: appleboy/ssh-action@master with: host: ${{ secrets.PROD_HOST }} username: ${{ secrets.PROD_USER }} key: ${{ secrets.PROD_SSH_KEY }} script: | cd /var/www/app ./deploy.sh ``` シンボリックリンクによる原子的デプロイは即時のロールバックを可能にします。Messengerワーカーは新コードを読み込ませるために再起動が必要です。 ## API PlatformとREST ### 質問23: API PlatformでREST APIをどう構築しますか? API PlatformはSymfonyでREST/GraphQL APIを構築する標準的な選択肢で、自動ドキュメント生成とHTTP標準を提供します。 ```php // src/Entity/Article.php // API Platformリソース設定 namespace App\Entity; use ApiPlatform\Metadata\ApiResource; use ApiPlatform\Metadata\Delete; use ApiPlatform\Metadata\Get; use ApiPlatform\Metadata\GetCollection; use ApiPlatform\Metadata\Patch; use ApiPlatform\Metadata\Post; use ApiPlatform\Metadata\Put; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Serializer\Attribute\Groups; use Symfony\Component\Validator\Constraints as Assert; #[ORM\Entity(repositoryClass: ArticleRepository::class)] #[ApiResource( operations: [ new GetCollection( normalizationContext: ['groups' => ['article:list']], ), new Get( normalizationContext: ['groups' => ['article:read']], ), new Post( security: "is_granted('ROLE_AUTHOR')", denormalizationContext: ['groups' => ['article:write']], ), new Put( security: "is_granted('ARTICLE_EDIT', object)", ), new Patch( security: "is_granted('ARTICLE_EDIT', object)", ), new Delete( security: "is_granted('ARTICLE_DELETE', object)", ), ], order: ['publishedAt' => 'DESC'], paginationItemsPerPage: 20, )] class Article { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] #[Groups(['article:list', 'article:read'])] private ?int $id = null; #[ORM\Column(length: 255)] #[Assert\NotBlank] #[Assert\Length(min: 10, max: 255)] #[Groups(['article:list', 'article:read', 'article:write'])] private ?string $title = null; #[ORM\Column(type: 'text')] #[Assert\NotBlank] #[Groups(['article:read', 'article:write'])] private ?string $content = null; #[ORM\ManyToOne(inversedBy: 'articles')] #[ORM\JoinColumn(nullable: false)] #[Groups(['article:list', 'article:read'])] private ?User $author = null; #[ORM\Column(nullable: true)] #[Groups(['article:list', 'article:read'])] private ?\DateTimeImmutable $publishedAt = null; } ``` ```php // src/State/ArticleProcessor.php // ビジネスロジック向けカスタムprocessor namespace App\State; use ApiPlatform\Metadata\Operation; use ApiPlatform\State\ProcessorInterface; use App\Entity\Article; use Symfony\Bundle\SecurityBundle\Security; use Symfony\Component\String\Slugger\SluggerInterface; final class ArticleProcessor implements ProcessorInterface { public function __construct( private readonly ProcessorInterface $persistProcessor, private readonly Security $security, private readonly SluggerInterface $slugger, ) {} public function process( mixed $data, Operation $operation, array $uriVariables = [], array $context = [] ): Article { if ($data instanceof Article && !$data->getId()) { // 新規記事: 著者とslugを設定 $data->setAuthor($this->security->getUser()); $data->setSlug($this->slugger->slug($data->getTitle())->lower()); } return $this->persistProcessor->process($data, $operation, $uriVariables, $context); } } ``` ```yaml # config/packages/api_platform.yaml api_platform: title: 'My API' version: '1.0.0' formats: jsonld: ['application/ld+json'] json: ['application/json'] docs_formats: jsonld: ['application/ld+json'] jsonopenapi: ['application/vnd.openapi+json'] html: ['text/html'] defaults: pagination_items_per_page: 20 pagination_client_items_per_page: true pagination_maximum_items_per_page: 100 swagger: versions: [3] ``` API Platformは自動的にOpenAPIドキュメントを生成し、フィルタ・ページング・バリデーションを提供します。 ### 質問24: API Platformの操作をどうカスタマイズしますか? API Platformでは、コントローラやState Provider/Processorを使ってカスタム操作を作成できます。 ```php // src/Entity/Article.php // カスタム操作 #[ApiResource( operations: [ // 標準操作 new GetCollection(), new Get(), // コントローラ付きカスタム操作 new Post( uriTemplate: '/articles/{id}/publish', controller: PublishArticleController::class, openapi: new Model\Operation( summary: '記事を公開', description: '記事のステータスを"published"に変更', ), security: "is_granted('ARTICLE_EDIT', object)", ), // カスタムState Provider付きの操作 new GetCollection( uriTemplate: '/articles/trending', provider: TrendingArticlesProvider::class, openapiContext: ['summary' => 'トレンド記事'], ), ], )] class Article { // ... } ``` ```php // src/Controller/PublishArticleController.php // カスタム操作のコントローラ namespace App\Controller; use App\Entity\Article; use Doctrine\ORM\EntityManagerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpKernel\Attribute\AsController; #[AsController] class PublishArticleController extends AbstractController { public function __construct( private readonly EntityManagerInterface $entityManager, ) {} public function __invoke(Article $article): Article { if ($article->getStatus() === 'published') { throw $this->createNotFoundException('記事は既に公開されています'); } $article->setStatus('published'); $article->setPublishedAt(new \DateTimeImmutable()); $this->entityManager->flush(); return $article; } } ``` ```php // src/State/TrendingArticlesProvider.php // カスタム読み取りロジック向けState Provider namespace App\State; use ApiPlatform\Metadata\Operation; use ApiPlatform\State\ProviderInterface; use App\Repository\ArticleRepository; final class TrendingArticlesProvider implements ProviderInterface { public function __construct( private readonly ArticleRepository $repository, ) {} public function provide(Operation $operation, array $uriVariables = [], array $context = []): array { // トレンド記事のためのカスタムロジック return $this->repository->createQueryBuilder('a') ->where('a.status = :status') ->andWhere('a.publishedAt > :date') ->setParameter('status', 'published') ->setParameter('date', new \DateTimeImmutable('-7 days')) ->orderBy('a.viewCount', 'DESC') ->setMaxResults(10) ->getQuery() ->getResult(); } } ``` State Providerは読み取りを、State Processorは書き込みを担当します。コントローラは複雑なケース向けに引き続き利用できます。 ### 質問25: 本番でのDBマイグレーションをどう管理しますか? Doctrineのマイグレーションはダウンタイムなしで実行でき、ロールバックが容易になるよう設計する必要があります。 ```php // migrations/Version20260202100000.php // 安全なマイグレーション: nullableカラムを追加 declare(strict_types=1); namespace DoctrineMigrations; use Doctrine\DBAL\Schema\Schema; use Doctrine\Migrations\AbstractMigration; final class Version20260202100000 extends AbstractMigration { public function getDescription(): string { return 'Add role column to users table (nullable first)'; } public function up(Schema $schema): void { // ステップ1: nullableカラムを追加 $this->addSql('ALTER TABLE users ADD role VARCHAR(50) DEFAULT NULL'); // CONCURRENTLYでindexを作成(PostgreSQL - 非ブロッキング) $this->addSql('CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_role ON users (role)'); } public function down(Schema $schema): void { $this->addSql('DROP INDEX IF EXISTS idx_users_role'); $this->addSql('ALTER TABLE users DROP COLUMN role'); } } ``` ```php // migrations/Version20260202100001.php // データマイグレーション(分離) final class Version20260202100001 extends AbstractMigration { public function getDescription(): string { return 'Populate role column with default value'; } public function up(Schema $schema): void { // 大規模テーブル向けのバッチ処理 $this->addSql("UPDATE users SET role = 'ROLE_USER' WHERE role IS NULL"); } public function down(Schema $schema): void { // データのロールバックは不要 } } ``` ```php // migrations/Version20260202100002.php // 最終マイグレーション: カラムをNOT NULLに final class Version20260202100002 extends AbstractMigration { public function getDescription(): string { return 'Make role column NOT NULL'; } public function up(Schema $schema): void { // 事前検証 $count = $this->connection->fetchOne('SELECT COUNT(*) FROM users WHERE role IS NULL'); if ($count > 0) { throw new \RuntimeException("$count users still have NULL role"); } $this->addSql('ALTER TABLE users ALTER COLUMN role SET NOT NULL'); $this->addSql("ALTER TABLE users ALTER COLUMN role SET DEFAULT 'ROLE_USER'"); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE users ALTER COLUMN role DROP NOT NULL'); $this->addSql('ALTER TABLE users ALTER COLUMN role DROP DEFAULT'); } } ``` ```bash # マイグレーション管理コマンド php bin/console doctrine:migrations:status # 状況を確認 php bin/console doctrine:migrations:migrate # マイグレーション実行 php bin/console doctrine:migrations:migrate prev # 直前にロールバック php bin/console doctrine:migrations:diff # スキーマからマイグレーション生成 php bin/console doctrine:migrations:execute --down # 個別ロールバック ``` expand-contract戦略(3回のデプロイ)はゼロダウンタイムを保証します: nullableを追加 → データ移行 → 制約を追加。 ## まとめ これら25問はSymfony面接の本質を、Service Containerの基本から高度な本番運用パターンまで網羅しています。 準備チェックリスト: - ✅ Service Containerと依存性注入 - ✅ Doctrine ORM: 関連、クエリ、フィルタ - ✅ セキュリティ: 認証、Voter、JWT - ✅ フォームとカスタムバリデーション - ✅ Messenger: 非同期処理とエラー処理 - ✅ テスト: ユニット、ファンクショナル、fixture - ✅ アーキテクチャ: CQRS、Repository Pattern - ✅ API Platform: REST、カスタム操作 - ✅ 本番運用: パフォーマンス、ログ、デプロイ > **さらに学ぶ** > > 各質問はSymfonyの公式ドキュメントでさらに掘り下げる価値があります。リクルーターはフレームワークのアーキテクチャ上の選択を理解し、技術的決定を説明できる候補者を高く評価します。 --- Source: SharpSkill (https://sharpskill.dev), tech interview preparation for your real stack. HTML version of this page: https://sharpskill.dev/ja/blog/symfony/symfony-interview-questions