2017-03-04 1 views
2

Db \ Adapter에 대한 팩터 리를 사용하기 위해 내 컨트롤러에서 ServiceManager 인스턴스를 가져 오려고합니다. 젠드 프레임 워크 3의 컨트롤러에서 서비스 관리자 인스턴스를 얻는 방법은 무엇입니까?

나는 모듈에 추가/응용 프로그램/설정/module.config.php :

'service_manager' => [ 
    'factories' => [ 
     Adapter::class => AdapterServiceFactory::class, 
    ], 
], 

나는 다음과 같은 라인을 추가/자동로드/local.php 파일 config (설정)하려면 지금

'db' => [ 
    'driver' => 'Mysqli', 
    'database' => 'mydb', 
    'username' => 'myuser', 
    'password' => 'mypassword', 
] 

를 I 내 모듈/Application/src/Controller/IndexController.php의 ServiceManager에 액세스하려고합니다. 어떻게해야합니까?

나는 $sm = $this->getPluginManager();을 시도했지만 성공하지 못했습니다.

Too few arguments to function Zend\Db\Adapter\Adapter::__construct(), 0 passed in (...)\vendor\zendframework\zend-servicemanager\src\Factory\InvokableFactory.php on line 30 and at least 1 expected 

내가 무엇을 할 수, 내 그 어댑터 객체를 얻을 것이다 ServiceManager에를 얻을 : 나는 PluginManager를 함께 $serviceManager->get(Adapter::class)를 실행하면 그것은 내게 오류를 준다?


제가

'controllers' => [ 
    'factories' => [ 
     Controller\IndexController::class => function(ContainerInterface $serviceManager) { 
      return new Controller\IndexController($serviceManager); 
     }, 
    ], 
], 

I 또한 module.config.php에 getServiceConfig() 메소드를 추가로

'controllers' => [ 
    'factories' => [ 
     Controller\IndexController::class => InvokableFactory::class, 
    ], 
], 

에서 컨트롤러 공장 변경 및 인 IndexController로 생성자를 첨가 ServiceManager를 수신합니다. 이제 컨트롤러 내부에 액세스 할 수 있습니다.

하지만 지금 내 질문이 있습니다. 더 좋고 더 좋은 "zend like"방법이 있습니까?

답변

4

SO의 위대한 관련 주제 덕분에 마침내 대답을 찾았습니다. ServiceManager in ZF3

컨트롤러 팩토리를 사용하여 마치 내가 한 것처럼 수행되는 것 같습니다.

+2

이 링크는 좋은 대답을주고 올바른 방법입니다.부가 메모 : 완벽한 서비스 관리자를 삽입하고 싶지는 않습니다. 그것은 귀하의 컨트롤러 untestable합니다. 이 예제에서 볼 수 있듯이 EntityManager 만 컨트롤러에 삽입됩니다. – xtreamwayz

+0

고맙습니다. 방금 테스트 해 봤어. 이제는 다른 수업에서 분리되었습니다. – Ctwx

+0

ZF3에서는 모든 서비스를 주입해야합니다. 심지어 양식에 직접 액세스 할 수도 없습니다. 전의. 컨트롤러에서는'new Form();'을 사용할 수 없습니다. –

0

저는 ZF1에 익숙하며 지금 ZF3을 배우고 있습니다. 구성 파일에 DB 구성을 설정 한 다음 컨트롤러에서 db 어댑터를 가져 오는 간단한 작업을하고 싶습니다. 공문서에는 다양한 맞춤 설정을위한 수백만 가지 옵션이 있으므로 시간이 많이 걸렸습니다. 그래서 나는 찾고있는 누군가를 도울 내 대답을 게시하고 있습니다.

1과 같이 config/autoload/global.php 또는 config/autoload/local.php에 DB 자격 증명을 추가 :에, 마지막으로

return [ 
    //... 
    'controllers' => [ 
     'factories' => [ 
      //... 
      // Add these lines 
      Controller\MycontrollernameController::class => function($container) {// $container is actually the service manager 
       return new Controller\MycontrollernameController(
        $container->get(\Zend\Db\Adapter\Adapter::class) 
       );// this will pass the db adapter to the controller's constructor 
      }, 
      //... 
     ] 
    ] 
    //... 
]; 

3 : module/YOUR_MODULE_NAME/config/module.config.php에서

<?php 
return [ 
    'db' => [ 
     'driver' => 'Pdo_Mysql',// can be "Mysqli" or "Pdo_Mysql" or other, refer to this link for the full list: https://docs.zendframework.com/zend-db/adapter/ 
     'hostname' => 'localhost',// optional 
     'database' => 'my_test_db', 
     'username' => 'root', 
     'password' => 'root', 
    ], 
]; 

2가, 컨트롤러 공장의 섹션이 추가 귀하의 컨트롤러 module/YOUR_MODULE_NAME/src/Controller/MycontrollernameController, 당신은 얻을 수있는 DB 어댑터를 사용 :

<?php 
namespace Application\Controller; 

use Zend\Mvc\Controller\AbstractActionController; 
use Zend\View\Model\ViewModel; 

use Zend\Db\Adapter\Adapter; 

class MycontrollernameController extends AbstractActionController 
{ 

    private $db; 

    public function __construct($db) 
    { 
     $this->db = $db; 
    } 

    public function indexAction() 
    { 
     $result = $this->db->query('SELECT * FROM `my_table`', Adapter::QUERY_MODE_EXECUTE); 
     echo $result->count();// output total result 
     return new ViewModel(); 
    } 
} 

컨트롤러에 대한 팩토리를 생성하여 동일한 결과를 얻는 또 다른 방법이 있으며 그 팩토리에는 db 어댑터를 컨트롤러에 전달합니다. 초보자를 위해 ZF3을 나처럼 안녕하세요 - 세계 수준에서 시험해 보았는데 너무 많이 생각합니다.

관련 문제