นี่คือวิธีง่ายๆในการสร้างลูกค้าใหม่ด้วยกลุ่มเริ่มต้นและร้านค้าปัจจุบัน
use Magento\Framework\App\RequestFactory;
use Magento\Customer\Model\CustomerExtractor;
use Magento\Customer\Api\AccountManagementInterface;
class CreateCustomer extends \Magento\Framework\App\Action\Action
{
/**
* @var RequestFactory
*/
protected $requestFactory;
/**
* @var CustomerExtractor
*/
protected $customerExtractor;
/**
* @var AccountManagementInterface
*/
protected $customerAccountManagement;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param RequestFactory $requestFactory
* @param CustomerExtractor $customerExtractor
* @param AccountManagementInterface $customerAccountManagement
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
RequestFactory $requestFactory,
CustomerExtractor $customerExtractor,
AccountManagementInterface $customerAccountManagement
) {
$this->requestFactory = $requestFactory;
$this->customerExtractor = $customerExtractor;
$this->customerAccountManagement = $customerAccountManagement;
parent::__construct($context);
}
/**
* Retrieve sources
*
* @return array
*/
public function execute()
{
$customerData = [
'firstname' => 'First Name',
'lastname' => 'Last Name',
'email' => 'customer@email.com',
];
$password = 'MyPass123'; //set null to auto-generate
$request = $this->requestFactory->create();
$request->setParams($customerData);
try {
$customer = $this->customerExtractor->extract('customer_account_create', $request);
$customer = $this->customerAccountManagement->createAccount($customer, $password);
} catch (\Exception $e) {
//exception logic
}
}
}