2013-06-04 2 views
2

유효성 검사 클래스에서 ServiceLocator를 얻고 싶습니다. 컨트롤러 인스턴스에서 가져 왔지만 null을 반환합니다.젠드 프레임 워크 2 : 유효성 검사 클래스에서 ServiceLocator를 얻는 방법

MyValidation.php 
namespace Register\Validator; 

use Zend\Validator\AbstractValidator; 
use Register\Controller\RegisterController; 

class MyValidation extends AbstractValidator { 

    /* 
    code... 
    */ 

    function isValid($value) 
    { 
     $controller = new RegisterController(); 
     $sm = $controller->getServiceLocator(); 
     $tableGateway = $sm->get('Register\Model\RegisterTable'); 
     $tableGateway->myValidationMethod($value); 

    } 

}

Module.php

public function getServiceConfig() 
{ 
    return array(
     'factories' => array(
      'Register\Model\RegisterTable' => function($sm) { 
       $tableGateway = $sm->get('RegisterTableGateway'); 
       $table = new RegisterTable($tableGateway); 
       return $table; 
      }, 
      'RegisterTableGateway' => function ($sm) { 
       $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); 
       $resultSetPrototype = new ResultSet(); 
       $resultSetPrototype->setArrayObjectPrototype(new RegisterUser()); 
       return new TableGateway('table-name', $dbAdapter, null, $resultSetPrototype); 
      }, 
     ), 
    ); 
} 

하지만 치명적인 오류 : 적절한 방법은 무엇 개체가 아닌
에() 멤버 함수를 얻기 위해 전화 모델 클래스에서 ServiceLocator를 얻으려면?

답변

7

유효성 검사기의 종속성을 검사기에 주입해야합니다. 폼 필드에 유효성 검사기를 할당 할 때 옵션 배열을 통해 그렇게 할 수 있습니다.

등록 \ 검사기 \ MyValidation : 은 내가 무슨 뜻인지 보여주기 위해 몇 가지 예제 코드를 작성

<?php 
namespace Application\Validator; 

use Zend\Validator\AbstractValidator; 

class MyValidation extends AbstractValidator 
{ 
    protected $tableGateway; 

    public function __construct($options = null) 
    { 
     parent::__constructor($options); 
     if ($options && is_array($options) && array_key_exists('tableGateway', $options)) 
     { 
      $this->tableGateway = $options['tableGateway']; 
     }   
    } 

    public function isValid($value) 
    { 
     // ... 
    } 
} 
당신이 중 하나를 수있는 ServiceLocatorAwareInterface을 구현 형태에 관해서는

때문에 자동으로 서비스 로케이터를 주입됩니다 폼의 팩토리를 사용하여 폼에 특정 종속성을 주입 할 수 있습니다.

등록 \ 양식 \ MyForm을 : 당신이 당신의 유효성 검사기 클래스의 컨트롤러를 인스턴스화하는 이유

<?php 
namespace Register\Form; 

use Zend\Form\Form; 
use Zend\InputFilter\InputFilterProviderInterface; 
use Zend\ServiceManager\ServiceLocatorAwareInterface; 

class MyForm extends Form implements InputFilterProviderInterface, ServiceLocatorAwareInterface 
{ 
    protected $servicelocator; 

    public function __construct() 
    { 
     $this->add(array(
       'name' => 'myfield', 
       'attributes' => array(
         'type' => 'text', 
       ), 
       'options' => array(
         'label' => 'Field 1' 
       ), 
      ) 
     ); 
    } 

    public function setServiceLocator(ServiceLocatorInterface $serviceLocator) 
    { 
     $this->servicelocator = $serviceLocator; 
    } 

    public function getServiceLocator() 
    { 
     return $this->servicelocator; 
    } 

    public function getInputFilterSpecification() 
    { 
     return array(
      'myfield' => array(
       'required' => true, 
       'filters'  => array(), 
       'validators' => array(
         array(
          'name' => 'Application\Validator\MyValidator', 
          'options' => array(
           'tableGateway' => $this->getServiceLocator()->get('Application\Model\RegisterTable'), 
          ), 
         ), 
       ), 
      ), 
     ); 
    } 
} 

은 또한 그것은 내게 분명하지 않다 여기

당신이 ServiceLocatorAwareInterface를 사용하여 할 것입니다 방법입니다. 당신은 정말로 그렇게해서는 안됩니다.

2

다른 접근 방식을 선택했습니다.

폼에서 유효성 검사기로 종속성을 전달하는 대신 폼에서 ValidatorManager로 전달합니다. ValidatorManager는 ServiceLocatorAware 인터페이스를 구현하는 각 유효성 검사기에 자동으로 주입됩니다.

<?php 

// Form 
public function getInputFilterSpecification(){ 
    $filter = new InputFilter(); 
    $factory = new InputFactory(); 

    // Inject SM into validator manager 
    $pm = $this->getServiceLocator()->get("ValidatorManager"); 

    $validatorChain = $factory->getDefaultValidatorChain(); 
    $validatorChain->setPluginManager($pm); 

    // Your validators here.. 
} 

// Validator 
class MyValidator extends AbstractValidator implements ServiceLocatorAwareInterface { 

    /** 
    * SM 
    * @var ServiceLocatorInterface 
    */ 
    private $serviceLocator; 

    /** 
    * Validate 
    */ 
    public function isValid($email){ 

     // Get the application config 
     $config = $this->getServiceLocator()->getServiceLocator()->get("config"); 

    } 

    /** 
    * ServiceLocatorAwarr method 
    * @param ServiceLocatorInterface $serviceLocator 
    * @return \Application\Module 
    */ 
    public function setServiceLocator(ServiceLocatorInterface $serviceLocator){ 
     $this->serviceLocator = $serviceLocator; 
     return $this; 
    } 

    /** 
    * ServiceLocatorAwarr method 
    * @return ServiceLocatorInterface 
    */ 
    public function getServiceLocator(){ 
     return $this->serviceLocator; 
    } 
}