新しいZF2アプリケーションを作成しています。私は、どこからでも呼び出しサービスのServiceLocator使用パターンがZF3から推奨されなくなったことに気付きました。 ZF3のコードを覚えておきたい。ZF3でLazy Loadingをセットアップするにはどうすればいいですか(どこからでもServiceLocatorパターンはありません)
コンストラクタ時にすべての依存関係を呼び出すようにコントローラを設定することができました。しかし、それはつまり、私が必要とする前に、先にDoctrine
オブジェクトを先に読み込むことを意味します。
質問
私はすぐにそれを必要とするとき、それが唯一ロードされるように、私はそれを設定するにはどうすればよいですか? (遅延読み込み)。私は、ZF3がコントローラの構築にロードを移すことを理解しています。そのため、ジャストインタイムをロードする方法は明らかになりません。
古いコード
class CommissionRepository
{
protected $em;
function getRepository()
{
//Initialize Doctrine ONLY when getRepository is called
//it is not always called, and Doctrine is not always set up
if (! $this->em)
$this->em = $this->serviceLocator->get('doctrine');
return $this->em;
}
}
現在のコードのServiceLocatorパターンのリファクタリング後
class CommissionRepository
{
protected $em;
function getRepository()
{
return $this->em;
}
function setRepository($em)
{
$this->em = $em;
}
function useRepository($id)
{
return $this->em->find($id);
}
}
class CommissionControllerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$parentLocator = $controllerManager->getServiceLocator();
// set up repository
$repository = new CommissionRepository();
$repository->setRepository($parentLocator->get('doctrine'));
// set up controller
$controller = new CommissionController($repository);
$controller->setRepository();
return $controller;
}
}
class CommissionController extends AbstractActionController
{
protected $repository;
public function setRepository(CommissionRepository $repository)
{
$this->repository = $repository;
}
public function indexAction()
{
//$this->repository already contains Doctrine but it should not
//I want it to be initialized upon use. How?
//Recall that it has been set up during Repository construction time
//and I cannot call it from "anywhere" any more in ZF3
//is there a lazy loading solution to this?
$this->repository->useRepository();
}
私はあなたが怠惰なセリフを探していると思います:http://framework.zend.com/manual/current/en/modules/zend.service-manager.lazy-services.html – marcosh
マニュアルに加えて、それは価値がありますZF3サービスマネージャ移行ガイドを読む - > http://zend-servicemanager.readthedocs.io/en/latest/migration/#lazy-services – Crisp