
Облікові записи клієнтів Magento 2 здебільшого створюються на фронтенді самими клієнтами. Однак можуть бути випадки, коли менеджерам магазинів потрібно створювати облікові записи клієнтів з панелі адміністратора.
Тим не менш, створення облікових записів клієнтів вручну може зайняти багато часу, якщо вам потрібно створити кілька. Таким чином, може бути зручніше створювати клієнтів у Magento 2 програмно.
Саме це ви дізнаєтесь сьогодні.
Створення клієнта за допомогою впровадження залежностей
Для початку ви можете створити клієнта програмно за допомогою методу впровадження залежностей. Просто скористайтеся наведеним нижче кодом:
<?php
declare(strict_types=1);
namespace Vendor\Module\Model;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Encryption\EncryptorInterface;
class CreateCustomerService
{
/**
* @var StoreManagerInterface
*/
protected $storeManager;
/**
* @var CustomerInterfaceFactory
*/
protected $customerFactory;
/**
* @var CustomerRepositoryInterface
*/
protected $customerRepository;
/**
* @var EncryptorInterface
*/
protected $encryptor;
/**
* @param StoreManagerInterface $storeManager
* @param CustomerInterfaceFactory $customerFactory
* @param CustomerRepositoryInterface $customerRepository
* @param EncryptorInterface $encryptor
*/
public function __construct(
StoreManagerInterface $storeManager,
CustomerInterfaceFactory $customerFactory,
CustomerRepositoryInterface $customerRepository,
EncryptorInterface $encryptor
){
$this->storeManager = $storeManager;
$this->customerFactory = $customerFactory;
$this->customerRepository = $customerRepository;
$this->encryptor = $encryptor;
}
/**
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function execute(): bool
{
// Get Website ID
$websiteId = $this->storeManager->getWebsite()->getWebsiteId();
// Instantiate object (this is the most important part)
$customer = $this->customerFactory->create();
$customer->setWebsiteId($websiteId);
// Preparing data for new customer
$customer->setEmail("email@domainnq.com");
$customer->setFirstname("First Name");
$customer->setLastname("Last name");
$hashedPassword = $this->encryptor->getHash('MyNewPass', true);
// Save data
try {
$this->customerRepository->save($customer, $hashedPassword);
} catch (\Exception $e) {
//log the error
return false;
}
return true;
}
}
Створення клієнта за допомогою менеджера об'єктів
Метод менеджер об'єктів – це ще один варіант, який ви можете розглянути. Хоча менеджер об'єктів здається більш простим, він має тенденцію приховувати справжні залежності класу. Тому ми рекомендуємо не використовувати його безпосередньо.
<?php
use Magento\Framework\App\Bootstrap;
require 'app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$storeId = $storeManager->getStore()->getId();
$websiteId = $storeManager->getStore($storeId)->getWebsiteId();
try {
$customer = $objectManager->get('\Magento\Customer\Api\Data\CustomerInterfaceFactory')->create();
$customer->setWebsiteId($websiteId);
$email = 'test11@example.com';
$customer->setEmail($email);
$customer->setFirstname("test first");
$customer->setLastname("test last");
$hashedPassword = $objectManager->get('\Magento\Framework\Encryption\EncryptorInterface')->getHash('MyNewPass', true);
$objectManager->get('\Magento\Customer\Api\CustomerRepositoryInterface')->save($customer, $hashedPassword);
$customer = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create();
$customer->setWebsiteId($websiteId)->loadByEmail($email);
} catch (Exception $e) {
echo $e->getMessage();
}
Ось так! Ви можете вибрати метод, з яким вам найзручніше працювати, і створювати клієнтів у Magento програмно набагато швидше.
Після створення клієнтів вам також може знадобитися створювати групи клієнтів програмно та призначати клієнтів .