如何在Magento 2中以编程方式添加客户?


13

我需要在Magento 2中以编程方式创建一个客户,但是我并没有发现太多文档。基本上,我需要做的就是将以下代码转换为“ Magento 2”:

$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();

$customer = Mage::getModel("customer/customer");
$customer   ->setWebsiteId($websiteId)
            ->setStore($store)
            ->setFirstname('John')
            ->setLastname('Doe')
            ->setEmail('jd1@ex.com')
            ->setPassword('somepassword');

try{
    $customer->save();
}

您想在独立脚本中执行此操作,还是拥有模型或其他内容?
马里斯(Marius)

@Marius,我一直在研究此模块,并创建了一个控制器。这个控制器我需要准备一些要保存的数据,其想法是调用客户模型并保存该信息。上面的代码可以放在控制器中,但我想对Magento 2一样。我仍然对Magento 2的新结构有些困惑,现在还停留在这里。我知道它与类注入有关和对象实例,但我不确定该怎么做...
Eduardo

Answers:


21

好的,过了一会儿我找到了解决方案,以防其他人需要它。Magento使用另一种实例化对象的方法,Magento 1.x中实例化对象的传统方法是使用“ Mage :: getModel(..)”,这已经在Magento 2中进行了更改。现在,Magento使用对象管理器实例化objets,我将不详细介绍其工作方式。.因此,在Magento 2中创建客户的等效代码如下所示:

<?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@domain.com"); 
        $customer->setFirstname("First Name");
        $customer->setLastname("Last name");
        $customer->setPassword("password");

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

希望这段代码可以帮助其他人。


6
你很亲近 您应该尽可能避免直接使用objectManager-这是一种错误的形式。做到这一点的正确方法是使用依赖注入来获取“ factory”类,并使用该类来创建实例。如果给定类不存在工厂类,则会自动生成。我已经编辑了使用此代码的代码(将工厂添加到构造函数和类中,并调用create()),并遵循PSR-2代码标准。
瑞安·霍尔

感谢您的纠正@RyanH。我考虑过使用工厂类,但不确定如何使用,因此我使用了objectManager ...我将阅读有关将来项目的PSR-2代码标准的更多信息。我现在将代码与您的更正配合使用,一切正常。谢谢
爱德华多2015年

@RyanH。完成; )
Eduardo

我可以在数据库中看到它,但在管理面板中却看不到它。发生了什么?
阿尼(Arni)2015年

1
@Arni; 我的第一个猜测是,您需要重新编制索引:)
Alex Timmer

4

这是使用默认组和当前商店创建新客户的简单方法。

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

这里的$ request是什么?我们还可以添加自定义属性吗?
Jafar Pinjar

如何设置自定义属性?
贾法尔·品哈尔(Jafar Pinjar)

0

此代码在外部文件或控制台文件CLI Magento中运行

namespace Company\Module\Console;

use Braintree\Exception;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Framework\App\Bootstrap;


class ImportProducts extends Command
{

    public function magentoStart()
    {
        $startMagento = $this->bootstrap();
        $state = $startMagento['objectManager']->get('Magento\Framework\App\State');
        $state->setAreaCode('frontend');
        return $startMagento['objectManager'];
    }

    protected function bootstrap()
    {
        require '/var/www/html/app/bootstrap.php';
        $bootstrap = Bootstrap::create(BP, $_SERVER);
        $objectManager = $bootstrap->getObjectManager();
        return array('bootstrap' => $bootstrap, 'objectManager' => $objectManager);
    }

    protected function createCustomers($item)
    {
        $objectManager      = $this->magentoStart();
        $storeManager       = $objectManager->create('Magento\Store\Model\StoreManagerInterface');
        $customerFactory    = $objectManager->create('Magento\Customer\Model\CustomerFactory');

        $websiteId  = $storeManager->getWebsite()->getWebsiteId();
        $customer   = $customerFactory->create();
        $customer->setWebsiteId($websiteId);
        $customer->setEmail("eu@mailinator.com");
        $customer->setFirstname("First Name");
        $customer->setLastname("Last name");
        $customer->setPassword("password");
        $customer->save();
    }
}

0

以上所有示例都可以使用,但是标准方法应该始终是使用服务合同而不是具体类。

因此,应优先采用以下方式以编程方式创建客户。

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

                /** @var \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository*/
                $customerRepository->save($customer);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.