Magento 2
Typehinting Variables
Free Preview
🟢 Good code
/**
 * By typehinting variables, intellisense can now find methods on a created
 * object. For example for factories, the object to typehint would be the
 * object class that is created from the factory.
 */

/** @var \Foo\Bar\Model\ResourceModel\Content\Collection $contentCollection */
$contentCollection = $this->_contentCollectionFactory->create()
    ->addAttributeToFilter(Content::ID, $this->getData('content_id'))
    ->addAttributeToSelect('*');

// ->count is found with intellisense
if ($contentCollection->count()) {
    $this->setData('content', $contentCollection->getFirstItem());
}
🔴 Bad code
/**
 * When creating specific objects, your IDE's intellisense will be unable to
 * find the proper method. This makes debugging difficult.
 */

$contentCollection = $this->_contentCollectionFactory->create()
    ->addAttributeToFilter(Content::ID, $this->getData('content_id'))
    ->addAttributeToSelect('*');

// ->count shows "Method 'count' not found" within IDE
if ($contentCollection->count()) {
    $this->setData('content', $contentCollection->getFirstItem());
}
Want to learn more?

Visit M.academy to learn much more about Magento, Laravel, PHP, Javascript, & Docker.

M.academy logo