Magento 2
Typehinting Variables
Free Preview
🟢 Good code
/**
 * By typehinting variables, intellisense can help find methods on a created
 * object. In this example, the typehinted object would be the object class
 * that is created from the factory.
 */

/** @var \Foo\Bar\Model\ResourceModel\Widget\Collection $widgetCollection */
$widgetCollection = $this->widgetCollectionFactory->create()
    ->addAttributeToFilter(Widget::ID, $this->getData('widget_id'));

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

$widgetCollection = $this->widgetCollectionFactory->create()
    ->addAttributeToFilter(Widget::ID, $this->getData('widget_id'));

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

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

M.academy logo