Leen Rihawi
Leen Rihawi

Reputation: 65

interface between two modules zend Framework

is there a way to create interfaces between 2 modules so that they can interact with one another? im working on zend framework2.

Many thanks.

Upvotes: 0

Views: 324

Answers (1)

Jurian Sluiman
Jurian Sluiman

Reputation: 13558

Zend Framework 2 offers a service manager. It allows you to register a specific service into the manager where other objects could use these services. Just for the sake of an example, you have a Blog module and a Twitter module. When you post a new blog post, you send a tweet using the Twitter module.

Say you have a Twitter service class which has the following interface:

namespace TwitterModule\Service;

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

class TwitterService implements TwitterServiceInterface
{
    // implementation
}

Now you can register this service inside the module.config.php of the Twitter module:

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

By this, any module could "ask" the service manager for the "TwitterService" and the service manager will return an instance of the TwitterModule\Service\TwitterService.

So, in your blog module:

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);
    }
}

The example might not be the best (you don't want a coupling like this, you'd prefer to solve it via events, you'd use proper dependency injection) but it just shows how instances could be shared between modules.

Upvotes: 1

Related Questions