多个对象实例化预防?

问题描述 投票:-1回答:1

我有一个带有用于存储对象的私有变量的类。我有一个函数,首先检查该变量是否已经包含一个对象;如果没有,它实例化所需的对象并将其设置为该变量,否则它只返回该变量的内容。

我想知道这里的getSessionCustomer()是否过度/不必要或者是否真的有益。我只是基于Zend的Album教程,但是我还没有完全测试它才真正看到优点(或缺点)。据我所知,文档中没有解释为什么包含这个附加功能。

class JobController extends AbstractActionController
{
    private $SessionCustomer;

    public function saveJobAction()
    {
        $SessionCustomer = $this->getSessionCustomer();

        if(empty($SessionCustomer->offsetGet('customer_id'))) {
            return $this->redirect()->toRoute('login');
        } else {
            $JobService = $this->getServiceLocator()->get('Job\Factory\JobServiceFactory');
            $job_id     = $JobService->saveJob();

            return $this->redirect()->toUrl('/job/' . $job_id); 
        }
    }

    public function viewJobAction()
    {
        $sm                 = $this->getServiceLocator();
        $SessionCustomer    = $this->getSessionCustomer();

        if(empty($SessionCustomer->offsetGet('customer_id'))) {
            return $this->redirect()->toRoute('login');
        } else {
            $JobTable       = $sm->get('Job\Model\JobTable');
            $JobItemTable   = $sm->get('Job\Model\JobItemTable');

            $jobId          = $this->params()->fromRoute('id');
            $Job            = $JobTable->getJobById($jobId);
            $JobItems       = $JobItemTable->getJobItemsByJobId($jobId);

            $this->layout()->setVariable('title', 'Order #' . $jobId);

            $viewModel = new ViewModel();
            $viewModel->setVariables(array(
                'Job' => $Job,
                'JobItems' => $JobItems
            ));

            return $viewModel;
        }
    }

    private function getSessionCustomer()
    {
        if(!$this->SessionCustomer) {
            $this->SessionCustomer = $this->getServiceLocator()->get('Session\Customer');
        }

        return $this->SessionCustomer;
    }
}
php oop object zend-framework2
1个回答
0
投票

我不认为这是一种矫枉过正,但我​​通常避免在控制器中调用getServiceLocator()。

您要问的是基本上确保满足控制器的依赖性要求。你可以使用Factory用于相同的目的,并采用更复杂的方式。您可以创建工厂并将依赖项直接注入控制器。这样你就永远不会调用非对象变量。

为此你需要创建一个实现FactoryInterface的类,它将有一个方法createService,它将为你提供ServiceLocator。您可以使用该serviceLocator获取所有依赖项并将它们直接注入您的类。

© www.soinside.com 2019 - 2024. All rights reserved.