Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

https://devdocs.magento.com/guides/v2.4/extension-dev-guide/api-concepts.html

https://docs.google.com/presentation/d/1L49RN2RXH55lBEpjsD2v5JWa1fALOmuP/edit?usp=share_link&ouid=112566144493030284998&rtpof=true&sd=true

Lý thuyết

Hợp đồng dịch vụ (Service Contracts)

...

Ví dụ Interface: Magento\Catalog\Api\ProductRepositoryInterface

Code Block
languagephp
public function delete(\Magento\Catalog\Api\Data\ProductInterface $product);

Ví dụ Model implements Interface: Magento\Catalog\Model\ProductRepository

Code Block
languagephp
public function delete(\Magento\Catalog\Api\Data\ProductInterface $product)
{
    $sku = $product->getSku();
    $productId = $product->getId();
    try {
        unset($this->instances[$product->getSku()]);
        unset($this->instancesById[$product->getId()]);
        $this->resourceModel->delete($product);
    } catch (ValidatorException $e) {
        throw new CouldNotSaveException(__($e->getMessage()));
    } catch (\Exception $e) {
        throw new \Magento\Framework\Exception\StateException(
            __('Unable to remove product %1', $sku)
        );
    }
    unset($this->instances[$sku]);
    unset($this->instancesById[$productId]);
    return true;
}

Việc model nào ứng với interface nào được cấu hình trong file etc/di.xml của magento 2.

Code Block
languagexml
<preference for="Magento\Catalog\Api\ProductRepositoryInterface" 
type="Magento\Catalog\Model\ProductRepository" />

...

Khi bạn truyền các tiêu chí tìm kiếm và gọi hàm getList (), một search results interface được trả về với kết quả tìm kiếm. Trong một search results interface thường chứa hàm getItems trả về một mảng các data entites (thực thể dữ liệu). Ví dụ, Hàm getItems () trong CustomerSearchResultsInterface trả về một mảng của các thực thể dữ liệu CustomerInterface. GroupSearchResultsInterface, hàm getItems () trả về một mảng các thực thể dữ liệu GroupInterface.

Code Block
languagephp
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Magento\Customer\Api\Data;

/**
 * Interface for customer search results.
 * @api
 */
interface CustomerSearchResultsInterface extends \Magento\Framework\Api\SearchResultsInterface
{
    /**
     * Get customers list.
     *
     * @return \Magento\Customer\Api\Data\CustomerInterface[]
     */
    public function getItems();

    /**
     * Set customers list.
     *
     * @param \Magento\Customer\Api\Data\CustomerInterface[] $items
     * @return $this
     */
    public function setItems(array $items);
}

...

Sau đây là một ví dụ về CustomerRepositoryInterface:

Code Block
languagephp
<?php
/**
 *
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Magento\Customer\Api;

/**
 * Customer CRUD interface.
 * @api
 */
interface CustomerRepositoryInterface
{
    /**
     * Create or update a customer.
     *
     * @param \Magento\Customer\Api\Data\CustomerInterface $customer
     * @param string $passwordHash
     * @return \Magento\Customer\Api\Data\CustomerInterface
     * @throws \Magento\Framework\Exception\InputException If bad input is provided
     * @throws \Magento\Framework\Exception\State\InputMismatchException If the provided email is already used
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function save(\Magento\Customer\Api\Data\CustomerInterface $customer, $passwordHash = null);

    /**
     * Retrieve customer.
     *
     * @param string $email
     * @param int|null $websiteId
     * @return \Magento\Customer\Api\Data\CustomerInterface
     * @throws \Magento\Framework\Exception\NoSuchEntityException If customer with the specified email does not exist.
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function get($email, $websiteId = null);

    /**
     * Get customer by customer ID.
     *
     * @param int $customerId
     * @return \Magento\Customer\Api\Data\CustomerInterface
     * @throws \Magento\Framework\Exception\NoSuchEntityException If customer with the specified ID does not exist.
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function getById($customerId);

    /**
     * Retrieve customers which match a specified criteria.
     *
     * This call returns an array of objects, but detailed information about each object’s attributes might not be
     * included. See http://devdocs.magento.com/codelinks/attributes.html#CustomerRepositoryInterface to determine
     * which call to use to get detailed information about all attributes for an object.
     *
     * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
     * @return \Magento\Customer\Api\Data\CustomerSearchResultsInterface
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria);

    /**
     * Delete customer.
     *
     * @param \Magento\Customer\Api\Data\CustomerInterface $customer
     * @return bool true on success
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function delete(\Magento\Customer\Api\Data\CustomerInterface $customer);

    /**
     * Delete customer by ID.
     *
     * @param int $customerId
     * @return bool true on success
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function deleteById($customerId);
}

...

Sau đây là ví dụ về CustomerMetadataInterface:

Code Block
languagephp
    <?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Magento\Customer\Api;

/**
 * Interface for retrieval information about customer attributes metadata.
 * @api
 */
interface CustomerMetadataInterface extends MetadataInterface
{
    const ATTRIBUTE_SET_ID_CUSTOMER = 1;

    const ENTITY_TYPE_CUSTOMER = 'customer';

    const DATA_INTERFACE_NAME = 'Magento\Customer\Api\Data\CustomerInterface';

}

Như vậy mình đã trình bày xong về mô hình Service Contracts trong Magento 2. Đây là một mẫu design pattern khá quan trọng trong Magento 2 mà mọi developer Magento 2 đều cần phải biết. Hiện tại, mô hình này đang được áp dụng rất phổ biến trong các module của Magento 2. Các bạn có thể tự xem thêm trong code core của Magento 2, cụ thể là 2 module Customer và Checkout để biết sâu thêm về các loại Data Interfaces và Service Interfaces trong mô hình này.

Bài tập

-Tạo module Magestore_Student

-Tạo bảng: student : id, name, class, university

-Tạo model, resource model, collection

-Tạo một data interface tên là StudentInterface, các method: setName, setId, setClass, getId, getName, getClass, getUniversity, setUniversity

-Tạo một service interface tên là StudentRepositoryInterface: method save(), getList(), delete()

-Tạo model Student implements StudentInterface và một model tên là StudentRepository implement StudentRepositoryInterface

-Tạo di.xml để mapping interface và model

-Sử dụng controller để test thử method save trên

APIAPI:

Tạo file etc/webapi.xml

url: tên đường dẫn khi gọi api

...

resource: dùng để xác thực, anonymous là bỏ qua xác thực

Ví dụ:

Code Block
languagexml
<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">

    <!-- Managing shipping guest information
-->
    <route url="/V1/guest-carts/:cartId/shipping-webpos/website/information" method="POSTGET">
        <service class="MagentoMagestore\CheckoutWebpos\Api\Website\GuestShippingInformationManagementInterfaceWebsiteInformationRepositoryInterface" method="saveAddressInformationgetInformation"/>
        <resources>
            <resource ref="anonymous" />
        </resources>
    </route>

</routes>

Call api:

Gọi đường dẫn:

http://[domain]/rest/default/V1/webpos/website/information với method là GET

để thực thi API

Bài tập:

  • Create database to store student data, design the table structure by yourself

  • Use service contract, write repository with the function getList, delete, deleteById,, getById, save

  • Create REST API , for all service interface to CRUD (Create, read , update, delete) student with resource anonymous.