Magento 2 ma wbudowany system Service Contracts oparty na interfejsach i Data Interfaces. Zamiast wstrzykiwać modele bezpośrednio, wstrzykujesz interfejsy Repository i Data Interface. To nie tylko dobre praktyki – to jedyny sposób żeby moduł działał stabilnie po aktualizacjach i był kompatybilny z innymi modułami. Pokażę jak poprawnie używać Service Contracts na przykładzie katalogu produktów.
Dlaczego nie używać modeli bezpośrednio
<?php
// Źle - bezpośrednia zależność od modelu
class BadOrderService
{
public function __construct(
private \Magento\Sales\Model\Order $order, // konkretny model
private \Magento\Sales\Model\ResourceModel\Order\Collection $collection, // kolekcja
) {}
// Problem 1: Model może zmienić API między wersjami
// Problem 2: Kolekcja ładuje wszystko do pamięci bez limitu
// Problem 3: Trudne do testowania (mock konkretnych klas)
// Problem 4: Brak gwarancji że inna implementacja (np. z rozszerzenia) działa tak samo
}
// Dobrze - zależność od interfejsów
class GoodOrderService
{
public function __construct(
private \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
private \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
) {}
}
Repository Interface – właściwy dostęp do danych
<?php
declare(strict_types=1);
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Api\SortOrderBuilder;
use Magento\Framework\Api\FilterBuilder;
class ProductService
{
public function __construct(
private ProductRepositoryInterface $productRepository,
private SearchCriteriaBuilder $searchCriteriaBuilder,
private SortOrderBuilder $sortOrderBuilder,
private FilterBuilder $filterBuilder,
) {}
// Pobierz produkt po ID - z cache Magento
public function getById(int $id): ProductInterface
{
return $this->productRepository->getById($id);
}
// Pobierz produkt po SKU
public function getBySku(string $sku): ProductInterface
{
return $this->productRepository->get($sku);
}
// Wyszukiwanie z filtrami i paginacją
public function getActiveByCategory(int $categoryId, int $page = 1, int $size = 20): array
{
$sortOrder = $this->sortOrderBuilder
->setField('created_at')
->setDescendingDirection()
->create();
$searchCriteria = $this->searchCriteriaBuilder
->addFilter('status', 1) // status = enabled
->addFilter('visibility', [2, 3, 4], 'in') // widoczne w katalogu
->addFilter('category_id', $categoryId)
->addSortOrder($sortOrder)
->setPageSize($size)
->setCurrentPage($page)
->create();
$result = $this->productRepository->getList($searchCriteria);
return [
'items' => $result->getItems(),
'total_count' => $result->getTotalCount(),
'page_size' => $size,
'current_page'=> $page,
];
}
}
Data Interface – tworzenie i modyfikacja
<?php
declare(strict_types=1);
use Magento\Catalog\Api\Data\ProductInterfaceFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
class ProductCreator
{
public function __construct(
private ProductInterfaceFactory $productFactory,
private ProductRepositoryInterface $productRepository,
) {}
public function create(array $data): \Magento\Catalog\Api\Data\ProductInterface
{
$product = $this->productFactory->create();
// Ustaw dane przez interfejs - nie przez magiczne metody
$product->setSku($data['sku']);
$product->setName($data['name']);
$product->setPrice($data['price']);
$product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
$product->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
$product->setTypeId('simple');
$product->setAttributeSetId(4); // Default attribute set
// Extension attributes - dla niestandardowych danych
$extensionAttributes = $product->getExtensionAttributes();
// $extensionAttributes->setStockItem(...);
return $this->productRepository->save($product);
}
public function updatePrice(string $sku, float $newPrice): void
{
$product = $this->productRepository->get($sku);
$product->setPrice($newPrice);
$this->productRepository->save($product);
}
}
Custom Service Contract – własny moduł
<?php
declare(strict_types=1);
// api/Data/LoyaltyPointsInterface.php
namespace Vendor\Loyalty\Api\Data;
interface LoyaltyPointsInterface
{
public const CUSTOMER_ID = 'customer_id';
public const POINTS = 'points';
public const EXPIRES_AT = 'expires_at';
public function getCustomerId(): int;
public function setCustomerId(int $customerId): self;
public function getPoints(): int;
public function setPoints(int $points): self;
public function getExpiresAt(): ?string;
public function setExpiresAt(?string $date): self;
}
// api/LoyaltyRepositoryInterface.php
namespace Vendor\Loyalty\Api;
interface LoyaltyRepositoryInterface
{
public function getByCustomerId(int $customerId): \Vendor\Loyalty\Api\Data\LoyaltyPointsInterface;
public function save(\Vendor\Loyalty\Api\Data\LoyaltyPointsInterface $points): \Vendor\Loyalty\Api\Data\LoyaltyPointsInterface;
public function deleteByCustomerId(int $customerId): bool;
}
<!-- etc/di.xml - powiąż interfejsy z implementacjami -->
<preference for="Vendor\Loyalty\Api\Data\LoyaltyPointsInterface"
type="Vendor\Loyalty\Model\LoyaltyPoints"/>
<preference for="Vendor\Loyalty\Api\LoyaltyRepositoryInterface"
type="Vendor\Loyalty\Model\LoyaltyRepository"/>
Podsumowanie
Service Contracts w Magento 2 to interfejsy które definiują publiczne API modułu. Repository Interface zapewnia dostęp do danych przez SearchCriteria zamiast bezpośrednich zapytań. Data Interface definiuje strukturę obiektu niezależnie od implementacji. Własny Service Contract to trzy elementy: Data Interface, Repository Interface i di.xml który łączy je z implementacją. To standard który sprawia że moduły są wzajemnie kompatybilne i odporne na aktualizacje.
