Skip to content

How to save data to database using interface repository api

I’m a newbie magento 2 developer. I’m currently learning how to store data to database using repository-interface-model-api approach. My code is not working.

model ItemRepository

    class ItemRepository implements ItemRepositoryInterface
{
    private $collectionFactory;

    protected $itemFactory;


    public function __construct(
        CollectionFactory $collectionFactory

    )
    {
        $this->collectionFactory = $collectionFactory;
    }

    public function getList()
    {
        return $this->collectionFactory->create()->getItems();
    }

    /**
     * {@inheritdoc}
     */
    public function save(ItemInterface $article)
    {
        try {
            /** @var Article $article */
            $article->getResource()->save($article);
        } catch (Exception $exception) {
            throw new CouldNotSaveException(
                __(sprintf('Could not save Article: %s', $exception->getMessage()))
            );
        }
        return $article;
    }

Api – Data ItemInterface

interface ItemInterface
{
    const ARTICLE_ID            = 'article_id';
    const TITLE                 = 'title';
    const CONTENT               = 'content';
    const CREATED_AT            = 'created_at';
    
   /**
     * Get Title
     *
     * @return string|null
     */
    public function getTitle();

    /**
     * Get Content
     *
     * @return string|null
     */
    public function getContent();

    /**
     * Get Created At
     *
     * @return string|null
     */
    public function getCreatedAt();

    /**
     * Get ID
     *
     * @return int|null
     */
    public function getId();

    /**
     * Set Title
     *
     * @param string $title
     * @return $this
     */
    public function setTitle($title);

    /**
     * Set Content
     *
     * @param string $content
     * @return $this
     */
    public function setContent($content);

    /**
     * Set Crated At
     *
     * @param int $createdAt
     * @return $this
     */
    public function setCreatedAt($createdAt);

    /**
     * Set ID
     *
     * @param int $id
     * @return $this
     */
    public function setId($id);
}

Api – ItemRepository

interface ItemRepositoryInterface
{
    /**
     * @return TestMymoduleApiDataItemInterface[]
     */
    public function getList();

    /**
     * @param ItemInterface $article
     * @return ItemInterface
     */
    public function save(ItemInterface $article);

}

Model-ResourceModel-Item – Collection

class Collection extends AbstractCollection
{
    
    protected function _construct()
    {
        $this->_init(
            Item::class,
            ItemResource::class
        );
    }
}

Model-ResourceModel-Item

class Item extends AbstractDb 
{
    protected function _construct()
    {
        $this->_init('test', 'article_id');
    }
}

Model-Item

class Item extends AbstractModel implements ItemInterface, IdentityInterface
{


    /**
     * Post Initialization
     * @return void
     */
    protected function _construct()
    {
        $this->_init(Item::class);
    }

  /**
     * Get Title
     *
     * @return string|null
     */
    public function getTitle()
    {
        return $this->getData(self::TITLE);
    }

    /**
     * Get Content
     *
     * @return string|null
     */
    public function getContent()
    {
        return $this->getData(self::CONTENT);
    }

    /**
     * Get Created At
     *
     * @return string|null
     */
    public function getCreatedAt()
    {
        return $this->getData(self::CREATED_AT);
    }

    /**
     * Get ID
     *
     * @return int|null
     */
    public function getId()
    {
        return $this->getData(self::ARTICLE_ID);
    }

    /**
     * Return identities
     * @return string[]
     */
    public function getIdentities()
    {
        return [self::CACHE_TAG . '_' . $this->getId()];
    }

    /**
     * Set Title
     *
     * @param string $title
     * @return $this
     */
    public function setTitle($title)
    {
        return $this->setData(self::TITLE, $title);
    }

    /**
     * Set Content
     *
     * @param string $content
     * @return $this
     */
    public function setContent($content)
    {
        return $this->setData(self::CONTENT, $content);
    }

    /**
     * Set Created At
     *
     * @param string $createdAt
     * @return $this
     */
    public function setCreatedAt($createdAt)
    {
        return $this->setData(self::CREATED_AT, $createdAt);
    }

    /**
     * Set ID
     *
     * @param int $id
     * @return $this
     */
    public function setId($id)
    {
        return $this->setData(self::ARTICLE_ID, $id);
    }
}

di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="TestMymoduleApiDataItemInterface" type="TestMymoduleModelItem"/>
    <preference for="TestMymoduleApiItemRepositoryInterface" type="TestMymoduleModelItemRepository"/>
</config>

webapi.xml

<?xml version="1.0"?>
<routes>
    <route url="/V1/article" method="GET">
        <service class="TestMymoduleApiItemRepositoryInterface" method="getList"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>

     <route url="/V1/article" method="POST">
        <service class="TestMymoduleApiItemRepositoryInterface" method="save"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

api call:POST http://localhost/rest/V1/article?title=Test title&content=test content

Any idea what is wrong with my code?
Thanks in advance