duansen6750 2019-06-05 06:59
浏览 51

如何在PHP包中访问Doctrine?

I'm creating a PHP package that will reside in the /vendor directory and it needs to access the database using Doctrine. In my main Symfony 4.2 code, I can access the database by using autowiring in the constructors like this:

public function __construct(EntityManagerInterface $em)

However, this only works with Symfony and does not seem to work inside public bundles. Please note that I need to access the default database connection, I do not want to create a new connection if one already exists.

I am trying to create a package that will work both with and without Symfony, so what I really need is the raw PHP to get the current database connection (not a new connection) without all the autowiring magic.

If the package is running under Symfony, it should use the current Symfony database connection. If not, it should create its own connection.

For example, I can open a new connection like this:

$conn = \Doctrine\DBAL\DriverManager::getConnection($params, $config)

That works fine, but I need a way to get the current Symfony database connection (something like this):

$conn = \Doctrine\DBAL\DriverManager::getCurrentConnection()

Unfortunately, there is no such function and I can't figure out how to create my own version of it.

  • 写回答

3条回答 默认 最新

  • doufei8691 2019-06-05 07:08
    关注

    You should define the class as a service and inject the EntityManager as an argument:

    # vendor/Acme/HelloBundle/Resources/Config/services.yml
    
    services:
        acme_hellp.service_id:
            class: Acme\HelloBundle\Class   
            arguments: ['@doctrine.orm.entity_manager']   
    
    
    // src/Acme/HelloBundle/DependencyInjection/AcmeHelloExtension.php
    
    namespace Acme\HelloBundle\DependencyInjection;
    
    use Symfony\Component\DependencyInjection\ContainerBuilder;
    use Symfony\Component\DependencyInjection\Extension\Extension;
    
    class AcmeHelloExtension extends Extension
    {
        public function load(array $configs, ContainerBuilder $container)
        {
            $loader = new XmlFileLoader(
               $container,
               new FileLocator(__DIR__.'/../Resources/config')
            );
            $loader->load('services.xml');
        }
    }
    

    Also, check this documentation on the Symfony site how to load your config files: https://symfony.com/doc/current/bundles/extension.html

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测