Magento 2
Saving Data Objects
Free Preview
🟢 Good code
<?php
/**
 * Save data objects (aka models) with resource models. This creates a
 * separation of concerns, so models only represent their entities, and only
 * resource models interact with the database. To ensure new objects are always
 * saved to the database, create the new data entities with factory classes.
 */
namespace Foo\Bar\Controller\Baz;

use Foo\Bar\Model\Widget;
use Foo\Bar\Model\WidgetFactory;

/**
 * Be sure to use a class alias to differentiate a widget model object from a
 * resource model object.
 */
use Foo\Bar\Model\ResourceModel\Widget as WidgetResource;

class Index
{
    /** @var WidgetFactory */
    private $widgetFactory;

    /** @var WidgetResource */
    private $widgetResource;

    /**
     * @param WidgetFactory $widgetFactory
     * @param WidgetResource @widgetResource
     */
    public function __construct(
        WidgetFactory $widgetFactory,
        WidgetResource $widgetResource
    ) {
        $this->widgetFactory = $widgetFactory;
        $this->widgetResource = $widgetResource;
    }

    public function execute()
    {
        /**
         * Create a widget object from the factory object. This ensures a new
         * object is created every time the code is ran.
         */

        /** @var Widget $widget */
        $widget = $this->widgetFactory->create();
        $widget->setName('baz');

        /**
         * Save the widget with the resource model instead of directly from the
         * model. This practice seperates concerns of responsibility.
         */
        $this->widgetResource->save($widget);
    }
}
🔴 Bad code
<?php
/**
 * Data objects should not be responsible for saving themselves. Calling
 * `->save()` on a model entity is a deprecated practice.
 */
namespace Foo\Bar\Controller\Baz;

use Foo\Bar\Model\Widget;

class Index
{
    /** @var Widget */
    private $widget;

    /**
     * @param Widget $widget
     */
    public function __construct(Widget $widget) {
        $this->widget = $widget;
    }

    public function execute()
    {
        $this->widget->setName('baz');
        $this->widget->save();
    }
}
Want to learn more?

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

M.academy logo