Creating an upgrade data script (UpgradeData.php)

The upgrade data script is the last one to execute. We will use it to demonstrate the example of creating the sample entries for our Department and Employee entities.

We start by creating the app/code/Foggyline/Office/Setup/UpgradeData.php file with (partial) content as follows:

namespace FoggylineOfficeSetup;

use MagentoFrameworkSetupUpgradeDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;

class UpgradeData implements UpgradeDataInterface
{
    protected $departmentFactory;
    protected $employeeFactory;

    public function __construct(
        FoggylineOfficeModelDepartmentFactory $departmentFactory,
        FoggylineOfficeModelEmployeeFactory $employeeFactory
    )
    {
        $this->departmentFactory = $departmentFactory;
        $this->employeeFactory = $employeeFactory;
    }

    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        /* #snippet1 */
        $setup->endSetup();
    }
}

UpgradeData conforms to UpgradeDataInterface, which requires the implementation of the upgrade method that accepts two parameters of type ModuleDataSetupInterface and ModuleContextInterface. We are further adding our own __construct method to which we are passing DepartmentFactory and EmployeeFactory, as we will be using them within the upgrade method as shown next, by replacing /* #snippet1 */ with the following code:

$salesDepartment = $this->departmentFactory->create();
$salesDepartment->setName('Sales');
$salesDepartment->save();

$employee = $this->employeeFactory->create();
$employee->setDepartmentId($salesDepartment->getId());
$employee->setEmail('[email protected]');
$employee->setFirstName('John');
$employee->setLastName('Doe');
$employee->setServiceYears(3);
$employee->setDob('1983-03-28');
$employee->setSalary(3800.00);
$employee->setVatNumber('GB123456789');
$employee->setNote('Just some notes about John');
$employee->save();

The preceding code creates an instance of the department entity and then saves it. An instance of employee is then created and saved, passing it the newly created department ID and other attributes.

Tip

A more convenient and professional-looking approach for saving an entity could be given as follows:

$employee->setDob('1983-03-28')
    ->setSalary(3800.00)
    ->setVatNumber('GB123456789')
    ->save();

Here, we are utilizing the fact that each of the entity setter methods returns $this (an instance of the entity object itself), so we can chain the method calls.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.84.29