首先,请注意,我的意图是不对构造函数使用任何注入。
我无法使用getParameter
,因为配置来自数据库。
我自己解释一下:
我在数据库中创建了一个整个应用程序通用的配置表,我需要在每个控制器和每个监听器中获取数据。所以我正在寻找的东西就像symfony with doctrine一样全球化。
$this->getDoctrine
,但我想要$this->myconfiguration
有可能这样做吗?还是有更好的选择吗?
由于
答案 0 :(得分:0)
感谢@ccKep的回答,我可以回答我的问题,希望能帮助别人。
首先,我们在services.yml
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
public: false # Allows optimizing the container by removing unused services; this also means
# fetching services directly from the container via $container->get() won't work.
# The best practice is to be explicit about your dependencies anyway.
app.configuration:
class: App\Service\Configuration
arguments:
- "@doctrine.orm.entity_manager"
- "@service_container"
然后我们在src/service/Configuration.php
我还添加了文件缓存系统,以减少请求,因为这些请求将在整个应用程序中完成。
<?php
namespace App\Service;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Cache\Simple\FilesystemCache;
class Configuration
{
private $em;
private $container;
public function __construct(EntityManager $entityManager,ContainerInterface $container) {
$this->container = $container;
$this->em = $entityManager;
}
public function byID($id){
$cache = new FilesystemCache();
if (!$cache->has('configuration.id'.$id)) {
$configuration = $this->em->getRepository('App:Configuration')->find($id);
if (!$configuration) {
throw new \Exception('Ninguna Configuración encontrado con el ID ' . $id);
}
$cache->set('configuration.id'.$id, $configuration,3600);
}
$configuration=$cache->get('configuration.id'.$id);
dump($configuration);
die();
}
}
现在需要做的就是在任何控制器上请求服务
$configuration = $this->get("configuration")->byID(1);