dpklt4291 2016-09-06 13:00
浏览 55
已采纳

Doctrine Query Builder和Silex

In my Silex project I use the Doctrine Query Builder from the Database Abstraction Layer package.

"doctrine/dbal": "^2.5"

I register it in my application container like this.

/**
 * Make a connection to the database.
 */
$app['db'] = function() use($app) {
    $connectionParams = [
        'dbname' => $_ENV['DBNAME'],
        'user' => $_ENV['DBUSER'],
        'password' => $_ENV['DBPASS'],
        'host' => $_ENV['DBHOST'],
        'driver' => $_ENV['DBDRIVER'],
    ];

    return \Doctrine\DBAL\DriverManager::getConnection($connectionParams);
};

/**
 * Instantiate the query builder
 */
$app['db.builder'] = function() use($app) {
    return new \Doctrine\DBAL\Query\QueryBuilder($app['db']);
};

When I want to query for database records I am using a repository pattern and then inject the query builder instance into the repository and then I use the query builder in the repository my repositories are created like this.

$app['repository.user'] = function() use($app) {
    return new App\Repositories\UserRepository($app['db.builder']);
};

$app['repository.book'] = function() use($app) {
    return new App\Repositories\BookRepository($app['db.builder']);
};

In the user repository I query for an user to fetch the id and after that I query the book repository for the books that belong to the user, however the problem is that when I use the query builder in the book repository it is already filled with the previous user table. Do I need to reset the query builder instance or am I doing something wrong with registering the query builder into the container.

  • 写回答

2条回答 默认 最新

  • douyo770657 2016-09-06 13:14
    关注

    QueryBuilder is registered as a usual service and as such only one instance of it will be created. If you happen to populate any user data to it before you query some books, that's the way it is.

    To avoid this problem, you might define db.builder as a factory service*. That way, every time you request it, a new instance will be created:

    $app['db.builder'] = $app->factory(function () use ($app) {
        return new \Doctrine\DBAL\Query\QueryBuilder($app['db']);
    });
    

    Read more about service definitions in Silex at http://silex.sensiolabs.org/doc/master/services.html.

    *http://silex.sensiolabs.org/doc/master/services.html#factory-services

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器