【问题标题】:How can I include php code into my Controller in Symfony?如何在 Symfony 的控制器中包含 php 代码?
【发布时间】:2020-02-05 10:38:34
【问题描述】:

在我的控制器中,我有很多“使用”语句:

控制器.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';

但我收到错误消息:

警告:包括(App\Service\Namespace.php):无法打开流:否 这样的文件或目录

【问题讨论】:

  • 你为什么不使用它?使用 App\Service\Namespace.php ??

标签: php symfony namespaces include


【解决方案1】:

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

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

不过,您希望通过减少 use 语句的数量来清理您的类,这很好。当您的班级中有这么多use 语句时,这表明班级正在变得庞大而混乱,并且随着时间的推移将变得越来越难以维护。可以通过将类拆分为更小的类来解决此问题。例如,您可以将使用所有这些 Symfony\Component\Form 类的所有位置提取到一个新的表单类型类中,并仅使用这一个表单类型,而不是在控制器中构建整个表单。

【讨论】:

    猜你喜欢
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 2016-11-15
    • 2018-09-15
    • 1970-01-01
    • 2018-10-09
    • 2017-09-20
    相关资源
    最近更新 更多