0

I have successfully created a custom interface.

My model: app/code/Vendor/Samples/Model/Orders.php

class Orders extends \Magento\Framework\Model\AbstractModel implements OrdersInterface
{
    protected function _construct()
    {
        $this->_init('Vendor\Samples\Model\ResourceModel\Orders');
    }

    public function getSamples()
    {
        return $this->getData(self::SAMPLES); 
    }

}

My interface app/code/Vendor/Samples/Api/Data/OrdersInterface.php

interface OrdersInterface
{
    const SAMPLES = 'samples';

    public function getSamples();
}

The return data is ids serialized like this: ["9","10","11","12","13"].

Now my question.

I need to unserialize this data and use this as filter in a collection from another ressource.

Basically i need to extend $orders with getSamples() method and apply custom logic like this filter each time i use it.

public function getOrderColors()
{
    $samples = $this->serializer->unserialize($order->getSamples());
    return $this->colorsFactory->create()->getCollection()
        ->addFieldToFilter('id', ['in' => $samples]);
}

I can just apply filter manually in block each time i need it, but i think it would be better to implement this logic, so i can use $order->getSamples() everywhere.

What is the best way of doing this?

1 Answer 1

0

I found out i can make dependency injection in second controller like this.

File: app/code/Vendor/Samples/Model/Orders.php

protected function _construct()
{
    $this->_init('Vendor\Samples\Model\ResourceModel\Orders');
}

public function __construct(
    \Magento\Framework\Model\Context $context,
    \Magento\Framework\Registry $registry,
    \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
    \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
    \Vendor\Samples\Model\ColorsFactory $colorsFactory,
    \Magento\Framework\Serialize\SerializerInterface $serializer,
    array $data = []
) {
    $this->serializer = $serializer;
    $this->colorsFactory = $colorsFactory;
    parent::__construct(
        $context,
        $registry,
        $resource,
        $resourceCollection,
        $data
    );
}

And then i can create a method like this in the same file:

public function getSamples()
    {
        $samples = $this->serializer->unserialize($this->getData(self::SAMPLES));
        return $this->colorsFactory->create()->getCollection()
            ->addFieldToFilter('id', ['in' => $samples]);
    }

Now i can use $order->getSamples() everywhere and get expected results.

I am not sure this is best practice to accomplish this, but it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.