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)

...

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ậpAPI:

-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

API:

Tạo file etc/webapi.xml

url: tên đường dẫn khi Tạo file etc/webapi.xml

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

method: POST, PUT, GET, DELETE: phương thức gửi data lên api

...

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.