简体   繁体   中英

how to share model between ZF2 modules

I'm beginner in ZF2 world and I have following problem.

I'm writing browser game and I planned to create main MVC module, related to game Page rendering (eg Oveview page, Buildings page etc.). Different pages are generated by different Page\\Controllers. Everything fine.

But I also planned to add some engine-specific modules, eg User, Planet, Queue, which should implement only Model side of MVC (mean no View and no Controller). Simply implement Model to access database and share it with main MVC Page module, which render game pages.

I invented the way to put engine-specific module API into serviceManager, so Page controllers can access it (guess its common way for ZF2). For example I have User interface :

interface UserInterface
{
    public function Create ();
    public function Load ($player_id);
    public function Login ();
    public function Logout ();
}

and UserManager class which implements it :

class UserManager implements UserInterface
{
    ....

In my \\module\\User\\config\\module.config.php file I added factory, which shares UserManager to other modules :

return array (
    'service_manager' => array(
        'factories' => array(
            'UserManager' => function($sm) {                
                return new \User\UserManager ();
            },
        ),
    ),
);

Its okay. Page Controller now can access UserManager API by abusing serviceManager :

$user = $this->getServiceLocator()->get('UserManager');

But how I can share Module API between modules outside Controller ?

For example my UserManager require to do some actions with PlanetManager.

In other words I need nice zend-way to implement cross-Model interaction. Thanks.

I am unsure on the design of the UserInterface (it looks more like an API for a UserController ).

Nevertheless, if the UserManager is dependent on the PlanetManager , you can inject it as a dependency .

The easiest way would be to create a new factory, just as you have with the UserManager .

PlanetManager

class PlanetManager
{
  protected $userManager;

  public function __construct(UserManager $userManager)
  {
    $this->setUserManager($userManager);
  }

  public function setUserManager(UserManager $userManager);  
}

Module.php

return array (
    'service_manager' => array(
        'factories' => array(
            'UserManager' => function($sm) {                
                return new \User\UserManager ();
            },
            'PlanetManager' => function($sm) {
                $userManager = $sm->get('UserManager');

                return new PlanetManager($userManager);
            }
        ),
    ),
);

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