配置Symfony2和Doctrine

时间:2015-04-22 10:39:04

标签: php symfony doctrine-orm

我还是Symfony2和Doctrine的新手。我正在尝试配置我的Doctrine,以便我可以在Symfony2项目中使用它。

我创建了一个DatabaseRepository文件,我正在进行连接。当我执行此文件时,我收到一个错误:

Catchable fatal error: Argument 1 passed to DatabaseRepository::__construct() must be an instance of Doctrine\DBAL\Connection, none given, called in app/cache/dev/appDevDebugProjectContainer.php on line 2363

我的DatabaseRepository文件:

<?php

namespace Acme\DemoBundle\Doctrine;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DBALException;
use Psr\Log\LoggerInterface;

class DatabaseRepository
{
    /**
     * @var Connection
     */
    protected $db;

    /**
     * @var LoggerInterface
     */
    protected $logger;

    /**
     * @param Connection $connection
     * @param LoggerInterface $logger
     */
    public function __construct(
        Connection $connection,
        LoggerInterface $logger
    ) {
        $this->db = $connection;
        $this->logger = $logger;
    }
}

doctrine位于Vendor目录下。我使用use添加连接,但这仍然不起作用。

好的家伙很抱歉我认为这个问题不完整我会这些。

这就是我调用DatabaseRepository的地方:

namespace Acme\DemoBundle\Repository;

use Acme\DemoBundle\Doctrine\DatabaseRepository;

class TestRepo {

    public $doctrine;

    public function __construct(
        DatabaseRepository $databaseRepository
    ){
        $this->doctrine = $databaseRepository;
    }


    public function test()
    {

    }

} 

以下是服务:

<!-- Doctrine -->
<service id="database_repository"
         class="Acme\DemoBundle\Doctrine\DatabaseRepository">
        <argument type="service" id="Doctrine\DBAL\Connection" />
        <argument type="service" id="Psr\Log\LoggerInterface" />
</service>

<service id="test_repo"
         class="Acme\DemoBundle\Repository\TestRepo">
    <argument type="service" id="database_repository" />
</service>

如下面的评论中所述,我添加了用于我的database_repository服务的参数。

但现在我收到了这个错误:

Fatal error: Uncaught exception 'Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException' with message 'The service "jdatabase_repository" has a dependency on a non-existent service "doctrine\dbal\connection"

1 个答案:

答案 0 :(得分:2)

您的database_repository配置不包含映射构造函数参数的任何argument部分。简而言之,您不会提供DatabaseRepositoryLoggerInterface个实例的已重新参数。

有一个database_connection服务代表第一个服务。有关如何在Symfony中使用DBAL的更多信息here

因此,要将其添加到conf文件中,您应该像这样修改它:

<service id="database_repository"
         class="Acme\DemoBundle\Doctrine\DatabaseRepository">
    <argument type="service" id="database_connection" />
</service>

您还必须添加LoggerInterface实例,但这不是Symfony,因此您必须首先为此创建服务。

请参阅Service Container documentation以了解服务在Symfony2中的运作方式

相关问题