0

有没有办法在 2 个模块之间创建接口,以便它们可以相互交互?我正在研究zend framework2。

非常感谢。

4

1 回答 1

1

Zend Framework 2 提供了一个服务管理器。它允许您将特定服务注册到其他对象可以使用这些服务的管理器中。仅作为示例,您有一个博客模块和一个 Twitter 模块。当您发布新的博客文章时,您使用 Twitter 模块发送推文。

假设您有一个 Twitter 服务类,它具有以下接口:

namespace TwitterModule\Service;

interface TwitterServiceInterface
{
    public function tweet($text);
}

class TwitterService implements TwitterServiceInterface
{
    // implementation
}

module.config.php现在您可以在 Twitter 模块中注册此服务:

'service_manager' => array(
    'invokable' => array(
        'TwitterService' => 'TwitterModule\Service\TwitterService'
    ),
),

这样,任何模块都可以向服务管理器“询问”“TwitterService”,服务管理器将返回TwitterModule\Service\TwitterService.

因此,在您的博客模块中:

class BlogService
{
    public function store(array $data)
    {
        // create a $post, store it into DB

        // $sm is an instance of Zend\ServiceManager\ServiceManager
        $twitter = $sm->get('TwitterService');
        $tweet   = sprintf('Blogged: %s', $post->getTitle());
        $twitter->tweet($tweet);
    }
}

这个例子可能不是最好的(你不想要这样的耦合,你更愿意通过事件来解决它,你会使用适当的依赖注入)但它只是展示了如何在模块之间共享实例。

于 2014-06-25T20:56:25.663 回答