문제

I am a newbie to zend framework. I am worrying how to call a service,factory other than from a controller (or class which is not extended AbstractActionController).

I am using the ZfcUser module to authenticate users. Now I want to check wheather a user logged or not inside the ZfcUser\Form\Base class. I am unable to call the zfcUserAuthentication factory which inside the getControllerPluginConfig() in ZfcUser\Module

Please some one help me.

Thank you

도움이 되었습니까?

해결책

What you are looking at is the concept of Dependency Injection. Basically YOU need to make sure that the Services you create GAIN access to the Gateways or Services they need.

For example, if you have a Service that takes care about persisting your Entities (DataObjects) to the Database, then YOU need to make sure to "inject" the Database-Adapter into the ServiceObject.

Required Dependencies therefore should be set via Constructor injection, i.e.:

class MyService {
    public function __construct(DbAdapter $dbA) {
        // do stuff with $dbA
    }
}

And you create this via the ServiceManager

'service_manager' => array(
    'factories' => array(
        'MyService' => function($sm) {
             $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
             $service   = new MyService($dbAdapter);
             return $service;
         }
    )
)

And lastly you access your service via the ServiceManager (probably somewhere in your controller).

public function someAction() {
    $service = $this->getServiceLocator()->get('MyService');
    // do stuff with $service
}

다른 팁

You need to inject the services/classes that a given service/class depends on. In your case you should modify ZfcUser\Form\Base to either accept the class via the constructor or a setter function. Then you would modify the service factory that creates the instance of ZfcUser\Form\Base to inject the dependency.

For example:

ZfcUser\Form\Base

private $myDependency;

public function setMyDependency($dependency) {
    $this->myDependency = $dependency;
}

And if your using a closure in your service factory config something like:

'my_service_that_uses_zfcuser_form_base' => function($sm) {
    $form = new ZfcUser\Form\Base();
    $form->setMyDependency($sm->get('the_dependency_you_want'));
    return $form;
}

Avoid injecting the service manager, this is bad practice.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top