Magento2 自定义API

StepOne:新建UserRespositoryInterface类


namespace Lemon\Min\Api;

use Lemon\Min\Api\Data\UserInterface;

interface UserRespositoryInterface
{
    public function getById();
}

StepTwo:新建UserRespository类

 
namespace Lemon\Min\Model;

use Lemon\Min\Api\Data\UserInterface;
use Lemon\Min\Api\Data\UserInterfaceFactory;
use Lemon\Min\Api\UserRespositoryInterface;
use Lemon\Min\Model\ResourceModel\User\CollectionFactory as UserCollectionFactory;
use Lemon\Min\Model\ResourceModel\User as ResourceUser;

class UserRespository implements UserRespositoryInterface
{
    /**
     * @var UserFactory
     */
    protected $userFactory;
    /**
     * @var ResourceUser
     */
    protected $resource;
    /**
     * @var UserCollectionFactory
     */
    protected $userCollectionFactory;
    /**
     * @var UserInterfaceFactory
     */
    protected $userInterfaceFactory;

    public function __construct(
        ResourceUser $resource,
        \Lemon\Min\Model\UserFactory $userFactory,
        UserCollectionFactory $userCollectionFactory,
        UserInterfaceFactory $userInterfaceFactory
    ){
        $this->resource = $resource;
        $this->userFactory = $userFactory;
        $this->userCollectionFactory = $userCollectionFactory;
        $this->userInterfaceFactory = $userInterfaceFactory;
    }
    public function getById()
    {
        $user = $this->userInterfaceFactory->create();
        $collection = $user->getCollection();
        $connection = $collection->getConnection();
        $tbl = $connection->getTableName('wm_user');
        $select = $connection->select('name,sex')
                          ->from($tbl)
                          ->where('id=?',1);
        $res = $connection->fetchAll($select);
        $selectData = json_encode($res);//这是将数组转换为字符串的方法
        return $selectData;


    }
}

StepThree:新建UserInterface类


namespace Lemon\Min\Api\Data;

interface UserInterface
{
    const ID = 'id';
    const NAME = 'name';
    const SEX = 'sex';
    const TEL = 'tel';
    const EMAIL = 'email';
    /**#@-*/

    /**
     * Get user id
     *
     * @return int|null
     */
    public function getId();
    /**
     * Set user id
     *
     * @param int $id
     * @return $this
     */
    public function setId($id);
    /**
     * Get user name
     *
     * @return string|null
     */
    public function getName();
    /**
     * Set user name
     *
     * @param string $name
     * @return $this
     */
    public function setName($name);
    /**
     * Get user sex
     *
     * @return int|null
     */
    public function getSex();
    /**
     * Set user sex
     *
     * @param int $sex
     * @return $this
     */
    public function setSex($sex);
    /**
     * Get user tel
     *
     * @return int|null
     */
    public function getTel();
    /**
     * Set user tel
     *
     * @param int $tel
     * @return $this
     */
    public function setTel($tel);
    /**
     * Get user email
     *
     * @return string|null
     */
    public function getEmail();
    /**
     * Set user email
     *
     * @param string $email
     * @return $this
     */
    public function setEmail($email);
}

StepFour:修改User Model类


namespace Lemon\Min\Model;

use \Magento\Framework\Model\AbstractModel;
use Lemon\Min\Api\Data\UserInterface;



/**
 * Class User
 * @package Lemon\Min\Model
 */
class User extends AbstractModel implements UserInterface
{
    
    // const ID = 'id';

    protected function _construct()
    {
        $this->_init('Lemon\Min\Model\ResourceModel\User');
    }
    //implements CustomerInterface functions
    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->getData(UserInterface::ID);
    }

    /**
     * Set id
     *
     * @param $id
     * @return $this
     */
    public function setId($id)
    {
        return $this->setData(UserInterface::ID, $id);
    }
    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->getData(UserInterface::NAME);
    }

    /**
     * Set name
     *
     * @param $name
     * @return $this
     */
    public function setName($name)
    {
        return $this->setData(UserInterface::NAME, $name);
    }
     /**
     * Get sex
     *
     * @return int
     */
    public function getSex()
    {
        return $this->getData(UserInterface::SEX);
    }

    /**
     * Set sex
     *
     * @param $sex
     * @return $this
     */
    public function setSex($sex)
    {
        return $this->setData(UserInterface::SEX, $sex);
    }
     /**
     * Get tel
     *
     * @return int
     */
    public function getTel()
    {
        return $this->getData(UserInterface::TEL);
    }

    /**
     * Set tel
     *
     * @param $tel
     * @return $this
     */
    public function setTel($tel)
    {
        return $this->setData(UserInterface::TEL, $tel);
    }
    /**
     * Get email
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->getData(UserInterface::EMAIL);
    }

    /**
     * Set email
     *
     * @param $email
     * @return $this
     */
    public function setEmail($email)
    {
        return $this->setData(UserInterface::EMAIL, $email);
    }
}

StepFive:修改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="Lemon\Min\Api\UserRespositoryInterface"
                type="Lemon\Min\Model\UserRespository" />
    <preference for="Lemon\Min\Api\Data\UserInterface"
                type="Lemon\Min\Model\User" />
</config>

StepSix:修改控制器


/**
 * user wumin
 */
namespace Lemon\Min\Controller\User;

// use Lemon\Min\Api\UserRespositoryInterface;

/**
 * Class Index
 *
 * @package Lemon\Min\Controller\User
 */
class Index extends \Magento\Framework\App\Action\Action
{
    // /**
    //  * @var UserRespository
    //  */
    // private $userRespository;
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;
    // /**
    //  * @var \Lemon\Min\Model\userFactory
    //  */
    // private $_userFactory;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
        // \Lemon\Min\Model\UserFactory $userFactory
        // UserRespositoryInterface $userRespository
    ) {

        $this->resultPageFactory = $resultPageFactory;
        // $this->_userFactory = $userFactory;
        // $this->userRespository = $userRespository;
        parent::__construct($context);
    }

    /**
     * Execute
     *
     * @return void
     */
    public function execute()
    {
        // //********************************************
        // /**
        //  * 1、下面展示了从Controller里直接调用Model的例子
        //  */
        // //Tips:创建Model实体 Lemon\Min\Model\user
        // $user = $this->_userFactory->create();
        // //Tips:获取Collection Lemon\Min\Model\ResourceModel\User\Collection
        // $collection = $user->getCollection();
        // foreach($collection as $item){
        //     //这是获取全部数据
        //     $itemData = $item->getData();
        //     //这是获取某个字段数据
        //     $itemName = $itemData['name'];
        //     print_r($itemName);
        //     echo '

';
// } // //上面的操作把Customer表的所有数据一次全部查出来,collection类的方法不是很灵活,那么怎么根据条件查询数据? // $conn = $collection->getConnection(); // $tbl = $conn->getTableName("wm_user"); // $select = $conn->select() // ->from($tbl) // ->where('id=?',1);//需要占位符 // $res = $conn->fetchAll($select); // print_r($res); // echo '

';
// //根据primaryKey查询数据 // //get user info by id // $id = 4; // //load()方法直接通过Model调用 // $userInfo = $user->load($id); // //获取全部信息 // $data = $userInfo->getData(); // // 获取单个字段信息 // $nameData = $data['name']; // print_r($nameData); // //************************************************** // /** // * 2、use Model and ResourceModel // */ // $user = $this->_userFactory->create(); // $userList = $user->getUserList(); // print_r($userList); // //********************************************************** // //use respository // $id = 4; // $userInfo = $this->userRespository->load($id); // $data = $userInfo->getData(); // $name = $data['name']; // print_r($name); return $this->resultPageFactory->create(); } }

StepSeven:修改Block



namespace Lemon\Min\Block\User\Data;

use Lemon\Min\Api\UserRespositoryInterface;
use Lemon\Min\Api\Data\UserInterface;




class User extends \Magento\Framework\View\Element\Template 
{

    /**
     * @var Lemon\Min\Api\UserRespositoryInterface
     */
    protected $userRespository;
//     // /**
//     //  * @var \Lemon\Min\Model\User
//     //  */
//     // protected $_userFactory;

   public function __construct(
       \Magento\Framework\View\Element\Template\Context $context,
    //    \Lemon\Min\Model\UserFactory $userFactory,
       \Lemon\Min\Api\UserRespositoryInterface $userRespository

   )
   {
    //    $this->_userFactory = $userFactory;
       $this->userRespository = $userRespository;
       parent::__construct($context);
   }
   protected function _prepareLayout(){
       $this->setText('Testing');
       $this->setName('min');
   }
    public function getById(){
        //$user = $this->userRespository->create();
        return $this->userRespository->getById();
    }
   
}

为什么要在这里添加一个UserInterface? 
1.用接口实现,可以方便的把这个model改成RestApi.
2.依赖注入实现的方式不同:
2-1:不定义接口要获取UserrModel的方法是:
$user = $this->_userFactory->create(); 通过Factory类获取实例
2-2:定义接口获取UseModel的方法是:
use Lemon\Min\Api\UserRespositoryInterface;
__construct()方法
UserRespositoryInterface $userRespitory
$this->_userRespository = $userRespitory;

你可能感兴趣的:(Magento2 自定义API)