问题描述:

I started with Doctrine2 usage in my projects. Howevery, I don't understand something. Normally, I am working with PHP classes and my problem is:

require_once 'bootstrap.php';

class test {

public function addEmployee($name, $lastname) {

$emp = new Employee();

$emp->name = $name;

... other code

$entityManager->persist($emp);

$entityManager->flush();

}

}

Gives error that entuty manager is noc declared as variable. But, when I include bootstrap.php in function, it works. Like this:

class test {

public function addEmployee($name, $lastname) {

require_once 'bootstrap.php';

$emp = new Employee();

$emp->name = $name;

... other code

$entityManager->persist($emp);

$entityManager->flush();

}

}

I think it will be really slow if I include that in each function, so my question is: Is there any other way to include 'bootstrap.php' for all functions in class?

网友答案:

Use dependency injection. For example

class Test {
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $em;

    public function __construct(\Doctrine\ORM\EntityManager $entityManager) {
        $this->em = $entityManager;
    }

    public function addEmployee($name, $lastname) {
        // snip

        $this->em->persist($emp);
        $this->em->flush();
    }
}

require_once 'bootstrap.php';
$test = new Test($entityManager);
相关阅读:
Top