[我们正在尝试找到在Symfony项目中实现具有特定问题的最佳方法。
在用户级别,我们的应用程序依赖于“帐户”学说实体,该实体在HTTP_HOST全局帮助下针对域属性(多域应用程序)加载。在域example.domain.tld上将加载匹配的实体和设置。
在devops级别,我们还需要同时使用多个帐户的CLI脚本进行批处理。
我们面临的问题是如何编写同时满足这两种需求的服务?
让我们用一个简化的例子来说明。对于用户级别,我们拥有此功能,并且一切正常:
Controller / FileController.php
public function new(Request $request, FileManager $fileManager): Response { ... $fileManager->addFile($file); ... }
Service / FileManager.php
public function __construct(AccountFactory $account) { $this->account = $account; }
Service / AccountFactory.php
public function __construct(RequestStack $requestStack, AccountRepository $accountRepository) { $this->requestStack = $requestStack; $this->accountRepository = $accountRepository; } public function createAccount() { $httpHost = $this->requestStack->getCurrentRequest()->server->get('HTTP_HOST'); $account = $this->accountRepository->findOneBy(['domain' => $httpHost]); if (!$account) { throw $this->createNotFoundException(sprintf('No matching account for given host %s', $httpHost)); } return $account; }
现在,如果我们想编写以下控制台命令,它将失败,因为
FileManager
仅接受AccountFactory
,而不接受帐户实体。
$accounts = $accountRepository->findAll(); foreach ($accounts as $account) { $fileManager = new FileManager($account); $fileManager->addFile($file); }
我们可以调整
AccountFactory
,但这会感觉不对...实际上,这甚至更糟,因为Account依赖关系在服务中更深入。
有人知道如何正确地做到这一点吗?
[我们正在尝试找到在Symfony项目中实施具有特定问题的最佳方法。在用户级别,我们的应用程序依赖于“帐户”学说实体,......>
作为一种好习惯,您应该为FileManager创建一个接口,并将此FileManagerInterface设置为依赖项注入(而不是FileManager)。比起,您可以具有遵循相同接口规则的不同类,但具有不同的构造函数。