在Symfony 4中如何在没有DoctrineBundle的情况下将DBAL Doctrine连接注册为服务 [英] How to register the DBAL Doctrine connection as a service without the DoctrineBundle in Symfony 4

查看:70
本文介绍了在Symfony 4中如何在没有DoctrineBundle的情况下将DBAL Doctrine连接注册为服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在尝试仅将Doctrine DBAL连接组件注册为Symfony4中的服务。

我不需要完整的DoctrineBundle symfony提供的功能,而只需要一部分它提供了基本的数据库抽象级别。

现在,我要弄清楚如何实现由作曲家下载的原始库作为服务。

这是Connection类应该的方式根据官方文档创建:


I'm trying to register only the Doctrine DBAL Connection component as a service in Symfony4.
I don't need the full DoctrineBundle symfony offers, but only the part which provides a basic database abstraction level.
Now I'm stuck on figuring out how to implement the raw library downloaded by composer as a service.
This is how the Connection class should be created, as from the official documentation:

<?php
$config = new \Doctrine\DBAL\Configuration();
//..
$connectionParams = array(
    'dbname' => 'mydb',
    'user' => 'user',
    'password' => 'secret',
    'host' => 'localhost',
    'driver' => 'pdo_mysql',
);
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);

如果可能,如何在service.yml配置中配置这种类型的服务? br>
如果不是,那我该怎么办?

If it is possible, how do I configure this type of service in the service.yml configuration?
If it is not, how do I proceed then?

推荐答案

使用学说捆绑包,并从配置文件中删除orm部分。

You might be better off just using the doctrine bundle and removing the orm section from the config file. Does not really add much overhead and is easier that doing it yourself.

话虽如此,这是最小的dbal设置的详细信息

Having said that, here are the details for a minimal dbal setup

composer create symfony/skeleton s40dbal
cd s40dbal
composer require server
composer require doctrine/dbal

# .env
DB_URL=mysql://user:password@localhost/dbname

# config/services.yaml
Doctrine\DBAL\Configuration:

Doctrine\DBAL\Connection:
    factory: 'Doctrine\DBAL\DriverManager::getConnection'
    arguments:
        -
            url : '%env(DB_URL)%'
            driverOptions: {20: false} # emulate prepared statements
        - '@Doctrine\DBAL\Configuration'

# DefaultController.php
use Doctrine\DBAL\Connection;
class DefaultController
{
    public function index(Connection $conn)
    {
        $stmt = $conn->prepare('SELECT id,name FROM users WHERE username = ?');
        $stmt->execute(['someuser']);
        $row = $stmt->fetch();
        var_dump($row);

        return new Response('dbal');
    }
}

享受

这篇关于在Symfony 4中如何在没有DoctrineBundle的情况下将DBAL Doctrine连接注册为服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆