Question

I have this resource model:

<?php
namespace namespace\module\Model\ResourceModel;


class Post extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
    /**
     * Date model
     * 
     * @var \Magento\Framework\Stdlib\DateTime\DateTime
     */
    protected $_date;

    /**
     * constructor
     * 
     * @param \Magento\Framework\Stdlib\DateTime\DateTime $date
     * @param \Magento\Framework\Model\ResourceModel\Db\Context $context
     */
    public function __construct(
        \Magento\Framework\Stdlib\DateTime\DateTime $date,
        \Magento\Framework\Model\ResourceModel\Db\Context $context
    )
    {
        $this->_date = $date;
        parent::__construct($context);
    }


    /**
     * Initialize resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('clubshop_login', 'id');
    }

    /**
     * Retrieves Post Name from DB by passed id.
     *
     * @param string $id
     * @return string|bool
     */
    public function getPostNameById($id)
    {
        $adapter = $this->getConnection();
        $select = $adapter->select()
            ->from($this->getMainTable(), 'name')
            ->where('id = :id');
        $binds = ['id' => (int)$id];
        return $adapter->fetchOne($select, $binds);
    }
    /**
     * before save callback
     *
     * @param \Magento\Framework\Model\AbstractModel|\Mageplaza\HelloWorld\Model\Post $object
     * @return $this
     */
    protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
    {
        $object->setUpdatedAt($this->_date->date());
        if ($object->isObjectNew()) {
            $object->setCreatedAt($this->_date->date());
        }
        return parent::_beforeSave($object);
    }
}

Now i want to call getPostNameById in my controller, and i don't know how.

Can anyone tell me how can I call this function in my controller?

Was it helpful?

Solution

Add your resource model as dependency for your controller and simply call the method you need.

class MyController extends Whatever 
{
    protected $postResourceModel;
    public function __construct(
        ....
        \Namespace\Module\Model\ResourceModel\Post $postResourceModel,
        ....
    ) {
        ....
        $this->postResourceModel = $postResourceModel;
        ....
    }
}

now you can use inside your controller this

$postId = 1;
$postName = $this->postResourceModel->getPostNameById($postId);
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top