简体   繁体   中英

ZF2 How to put adapter into registry

I an using zend classes in my application (without the mvc). I would like to put my adapter instance into a container and use it in my other classes. This is what i have now.

load.php

$adapter = new Zend\Db\Adapter\Adapter(array(
            'driver'   => 'pdo_mysql',
            'database' => DB_PREFIX.DB_NAME,
            'username' => DB_USER,
            'password' => DB_PW
    ));

How do i access $adapter in my other class?

OtherClass.php

 public class OtherClass{

     function __construct() {       
        //$adapter is needed here
        $this->_model = get_class($this);
        $this->sql = new Sql\Sql($this->dbo);
    }
}

Previously in ZF1 there is a Zend::Registry where i can set my variable. Then later access it again by calling the get method. However, i can't find similar cases in ZF2. I tried using ServiceManager but it seems not to be working in my scenario.

Appreciate any expert advices.

ZF2 does not have a Registry like ZF1 does. Instead we have what's called a ServiceManager . You should use this SM to inject your dependencies into your Services.

You can read more information on the SM here -> http://zf2.readthedocs.org/en/latest/modules/zend.service-manager.intro.html

I'd recommend checking out ZfcUser on github -> https://github.com/ZF-Commons/ZfcUser and checkout their Module.php file. It may help you get a better understanding of how a working example uses the SM to handle injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM