0

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 \Test\Mymodule\Api\Data\ItemInterface[]
     */
    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="Test\Mymodule\Api\Data\ItemInterface" type="Test\Mymodule\Model\Item"/>
    <preference for="Test\Mymodule\Api\ItemRepositoryInterface" type="Test\Mymodule\Model\ItemRepository"/>
</config>

webapi.xml

<?xml version="1.0"?>
<routes>
    <route url="/V1/article" method="GET">
        <service class="Test\Mymodule\Api\ItemRepositoryInterface" method="getList"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>

     <route url="/V1/article" method="POST">
        <service class="Test\Mymodule\Api\ItemRepositoryInterface" 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

1

1 Answer 1

0

The issue is in Model-Item class.

class Item extends AbstractModel implements ItemInterface, IdentityInterface
{
    /**
     * Post Initialization
     * @return void
     */
    protected function _construct()
    {
        $this->_init(Item::class);
    }

The _init function should be passed the class name of the ResourceModel for the Item.

Modifie it to below code:

class Item extends AbstractModel implements ItemInterface, IdentityInterface
{
    /**
     * Post Initialization
     * @return void
     */
    protected function _construct()
    {
        $this->_init(ResourceModel\Item::class);
    }

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.