How to add a customer programmatically in Magento 2?

Okay, after a while I found a solution in case someone else needs it.. Magento uses another approach to instantiate objects, the traditional way to instantiate objects in Magento 1.x was using "Mage::getModel(..)", this have changed in Magento 2. Now Magento uses an object manager to instantiate objets, I won't enter in details about how it works.. so, the equivalent code for creating customers in Magento 2 would look like this:

<?php

namespace ModuleNamespace\Module_Name\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @var \Magento\Customer\Model\CustomerFactory
     */
    protected $customerFactory;

    /**
     * @param \Magento\Framework\App\Action\Context      $context
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Customer\Model\CustomerFactory    $customerFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory
    ) {
        $this->storeManager     = $storeManager;
        $this->customerFactory  = $customerFactory;

        parent::__construct($context);
    }

    public function execute()
    {
        // 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 protected]"); 
        $customer->setFirstname("First Name");
        $customer->setLastname("Last name");
        $customer->setPassword("password");

        // Save data
        $customer->save();
        $customer->sendNewAccountEmail();
    }
}

Hope this snippet of code help someone else..


Here is simple way to create a new customer with default group and current store.

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' => '[email protected]',
        ];

        $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
        }
    }
}

All the above examples will work, but according to the coding standards you should always use service contracts than the concrete classes.

Hence, the following way should be preferred for creating customer account programmatically.


use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Store\Model\StoreManagerInterface;

class CustomerCreate
{
    public $store;

    public $customerFactory;

    public $customerRepository;

    public function __construct(
        StoreManagerInterface $store,
        CustomerInterfaceFactory $customerFactory,
        CustomerRepositoryInterface $customerRepository
    ) {
        $this->store = $store;
        $this->customerFactory = $customerFactory;
        $this->customerRepository = $customerRepository;
    }


    public function create()
    {
        try {
           /** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
           $customer = $this->customerFactory->create();
           $customer->setStoreId($this->store->getStoreId());
           $customer->setWebsiteId($this->store->getWebsiteId());
           $customer->setEmail($email);
           $customer->setFirstname($firstName);
           $customer->setLastname($lastName);

           /** @var \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository*/
           $customer = $this->customerRepository->save($customer);
           // Note: The save returns the saved customer object, else throws an exception.
       } catch (\Exception $e) {
          // Add log
       }
    }

}

Tags:

Magento 2.0