0

プロジェクトで Doctrine2 を使用することから始めました。しかし、私は何かを理解していません。通常、私はPHPクラスで作業していますが、私の問題は次のとおりです。

require_once 'bootstrap.php';
class test {

   public function addEmployee($name, $lastname) {
          $emp = new Employee();
          $emp->name = $name;
          ... other code
          $entityManager->persist($emp);
          $entityManager->flush();
   }

}

エンティティ マネージャが noc 変数として宣言されているというエラーが発生します。しかし、関数にbootstrap.phpを含めると機能します。このような:

class test {

   public function addEmployee($name, $lastname) {

          require_once 'bootstrap.php';

          $emp = new Employee();
          $emp->name = $name;
          ... other code
          $entityManager->persist($emp);
          $entityManager->flush();
   }

}

それを各関数に含めると非常に遅くなると思うので、私の質問は次のとおりです。クラス内のすべての関数に「bootstrap.php」を含める他の方法はありますか?

4

1 に答える 1

0

依存性注入を使用します。例えば

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);
于 2013-09-09T05:34:13.513 に答える