Obervers

The chapter subjects describe when and how a subject is needed and how a subject can get implemented.

When do I need an observer?

The subject itself does not implement the main business logic of the import; instead, it is the responsibility of the observers.

For this purpose, we implement a separate observer if the following apply:
  • You want to load data from the database based on the values found in the import file

  • You want to load data to make it available to subsequent observers or subjects

  • You want to persist data collected from values in one row of an import file

You need an observer to manipulate the data of a line.

How to implement an observer?

  • To get extended by our first Observer implementation, TechDivision\Import\Observers\AbstractObserver is the recommended tool

  • As a minimum requirement, an observer must implement the interface TechDivision\Import\Observers\ObserverInterface

Our sample observer will attempt to load the product with the SKU found in the current row and adds the SKU entity_id mapping to the topic.

Example

<?php

namespace TechDivision\Import\Product\Observers;

use TechDivision\Import\Utils\RegistryKeys;
use TechDivision\Import\Subjects\SubjectInterface;
use TechDivision\Import\Observers\AbstractObserver;

class MyObserver extends AbstractObserver
{

    /**
     * The product bunch processor instance.
     *
     * @var \TechDivision\Import\Product\Services\ProductBunchProcessorInterface
     */
    protected $processor;

    /**
     * Initialize the observer with the passed product bunch processor instance.
     *
     * @param \TechDivision\Import\Product\Services\ProductBunchProcessorInterface $productBunchProcessor The product bunch processor instance
     */
    public function __construct(ProductBunchProcessorInterface $processor)
    {
        $this->processor = $processor;
    }

    /**
     * Will be invoked by the subject once for every row.
     *
     * @param \TechDivision\Import\Subjects\SubjectInterface $subject The subject instance
     *
     * @return array The modified row
     * @see \TechDivision\Import\Observers\ObserverInterface::handle()
     */
    public function handle(SubjectInterface $subject)
    {

// initialize the row
        $this->setSubject($subject);
        $this->setRow($subject->getRow());

// try to load the product with the SKU of the actual row and store the entity ID => SKU mapping in the subject
        if ($product = $this->processor->loadProduct($this->getValue(ColumnKeys::SKU)){
        $this->subject->addSkuEntityIdMapping($product[MemberNames::ENTITY_ID], $product[MemberNames::SKU]);
    } else {
        throw new \Exception(sprintf('Can\'t load product with SKU "%s"', $sku));
    }

// return the processed row
        return $this->getRow();
    }
}