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

    评论

报告相同问题?