Question

I've been following article on Models and Resources here. According to my understanding, Magento2 uses service contract to provide model access to 3rd parties.

Here I'm interested in Data interface PostInterface.php which contains all constants and gettters/setter methods defined. Ex:

const POST_ID       = 'post_id';
const URL_KEY       = 'url_key'; 
public function getId();
public function getUrlKey();
public function setUrlKey($url_key);

Now these methods are also defined in the model Model/Post.php. Ex:

public function getUrlKey()
{
    return $this->getData(self::URL_KEY);
}

Questions:

  1. If a model request is made from 3rd party, it will hit interfaces function & interfaces function will model's function?
  2. Is it necessary to use interfaces here if my modules doesn't uses or isn't needed by any 3rd party?
  3. How these functions interact with each other internally? Is there any case where I can use interface function getUrlKey(), instead of model's getUrlKey() function, if I'm developing another module in Magento itself?
Was it helpful?

Solution

  1. 3rd party module should operate with your module's classes/interfaces marked as @api, not necessarily service contract interfaces, but preferably. If interface is requested in dependencies, Magento object manager resolves actual model to be instantiated according to preferences declared in di.xml (since interface itself cannot be instantiated). See official documentation
  2. It is recommended to declare service contract interfaces, read about benefits here and in official docs
  3. Is answered above (model implements interface). You should always use interfaces if available, even if those are defined in your module. This allows to manage complexity by limiting number of dependencies between classes/modules
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top