gpt4 book ai didi

php - 如何在 Symfony 中将 php 代码包含到我的 Controller 中?

转载 作者:行者123 更新时间:2023-12-04 16:59:05 24 4
gpt4 key购买 nike

在我的 Controller 中,我有很多“使用”语句:

Controller .php

namespace App\Controller; 



use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\Query\ResultSetMapping;
use App\Repository\PagesRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use App\Form\Type\ColorSelectorType;
use Symfony\Component\Form\Extension\Core\Type\FileType;

为了清理我的代码,我想把它们放在另一个页面上,比如服务。

一种方法是,将代码放在页面 Namespace.php 上并包含它:
  include 'App\Service\Namespace.php';

但我收到错误消息:

Warning: include(App\Service\Namespace.php): failed to open stream: No such file or directory

最佳答案

错误的直接原因是您使用相对路径来包含文件。始终在 __DIR__ 中使用绝对路径, 例如。

但是即使您提供了正确的路径,这仍然不起作用。你不能动 use语句到另一个文件。这些语句始终在当前文件的范围内起作用,而在其他任何地方都不起作用。

但是,您希望通过减少 use 的数量来清理您的类(class),这很好。声明。当你有这么多use类中的语句,它表明类变得越来越大和困惑,并且会随着时间的推移变得越来越难以维护。可以通过将类拆分为较小的类来解决此问题。例如,您可以提取使用所有这些 Symfony\Component\Form 的所有地方。类到一个新的表单类型类,并只使用这个表单类型而不是在 Controller 中构建整个表单。

关于php - 如何在 Symfony 中将 php 代码包含到我的 Controller 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58281315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com