...
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
API:
Tạo file etc/webapi.xml
...
Code Block | ||
---|---|---|
| ||
<?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 with resource anonymous.