问题描述
我正在尝试仅将 Doctrine DBAL Connection 组件注册为 Symfony4 中的服务.
我不需要完整的 DoctrineBundle symfony 提供,而只需要提供基本数据库抽象级别的部分.
现在,我一直在研究如何将 composer 下载的原始库实现为服务.
这就是应该如何创建 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 DoctrineDBALConfiguration();
//..
$connectionParams = array(
'dbname' => 'mydb',
'user' => 'user',
'password' => 'secret',
'host' => 'localhost',
'driver' => 'pdo_mysql',
);
$conn = DoctrineDBALDriverManager::getConnection($connectionParams, $config);
如果可以的话,如何在service.yml配置中配置这种类型的服务?
如果不是,那我该如何处理呢?
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
DoctrineDBALConfiguration:
DoctrineDBALConnection:
factory: 'DoctrineDBALDriverManager::getConnection'
arguments:
-
url : '%env(DB_URL)%'
driverOptions: {20: false} # emulate prepared statements
- '@DoctrineDBALConfiguration'
# DefaultController.php
use DoctrineDBALConnection;
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 中将 DBAL Doctrine 连接注册为没有 DoctrineBundle 的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!