小编den*_*smv的帖子

如何使用ZF3设置延迟加载(从任何地方都没有ServiceLocator模式)

我正在写一个新的ZF2应用程序.我注意到ZF3已经弃用了"从任何地方"调用服务的ServiceLocator使用模式.我想为ZF3编写代码.

我能够设置我的Controller在构造函数时调用所有依赖项.但这意味着Doctrine在我需要它之前加载ie 对象.

如何设置它以便仅在我需要它时立即加载?(延迟加载).我知道ZF3将加载移动到Controller构造,这使得如何加载Just-In-Time的东西并不明显.

旧代码

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

重构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) …
Run Code Online (Sandbox Code Playgroud)

deprecated service-locator zend-framework2 zend-framework3 zend-expressive

4
推荐指数
1
解决办法
1936
查看次数