简体   繁体   中英

How dynamic DB adapter working in ZF2?

In Zendframework 2, I have created new module MyModule as per this link: https://stackoverflow.com/a/17969889/2644574 to set DB adapter dynamically , It works fine.

But I never call MyModule module or any of function from this module.

Can any one explain me, How and When the DB adapter dynamically set without calling the module MyModule ?

The code you created in steps 1 to 4 from the link you provided are only the template for how to create the adapters. In step 5 they explain that you must add a function to your controller.

public function getYourTable()
{
    if (!$this->yourTable) {
        $sm = $this->getServiceLocator();
        $this->yourTable = $sm->get('YourModule\Model\YourTable');
    }       
    return $this->yourTable;
}

When you call that function the service manager is called and the adapter is created if it doesn't already exist. In the service manager's config is defined how to create these services and where to find them. They're then loaded via the autoloading capabilities of composer or the ZF2 module manager.

This is all possible because you registered the services with the global service manager through the function

getServiceConfig()

so for the service manager is doen't matter from which module the code comes from.

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