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、私はこのモジュールに取り組んでおり、コントローラーを作成しました。このコントローラーでは、保存するデータを準備する必要があります。アイデアは、顧客モデルを呼び出してその情報を保存することです。上記のコードは、Magento 2の場合と同じようにコントローラーに配置できます。Magento2の新しい構造と混同されて、今ここで止まってしまいます。とオブジェクトのインスタンスが、私はそれを行う方法がわからない
エドゥアルド

回答:


20

さて、しばらくして他の誰かがそれを必要とする場合の解決策を見つけました。Magentoはオブジェクトをインスタンス化する別のアプローチを使用します。Magento1.xでオブジェクトをインスタンス化する従来の方法は「Mage :: getModel Magento 2で変更されました。Magentoはオブジェクトマネージャーを使用してオブジェクトのインスタンスを作成します。その仕組みについては詳しく説明しません。したがって、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を直接使用することは避けてください。形式が悪いです。これを行う適切な方法は、依存関係注入を使用して「ファクトリー」クラスを取得し、それを使用してインスタンスを作成することです。指定されたクラスにファクトリクラスが存在しない場合は、自動生成されます。コードを編集してこれを使用し(コンストラクターとクラスにファクトリーを追加し、create()を呼び出します)、PSR-2コード標準に従います。
ライアンホール

訂正@RyanHをありがとう。ファクトリクラスを使用することを考えましたが、方法がわからなかったため、objectManagerを使用しました...将来のプロジェクトのPSR-2コード標準について詳しく読むことにします。私はあなたの修正でコードを使用していますが、すべてが完全に機能します。ありがとう
エドゥアルド

@RyanH。完了; )
エドゥアルド

データベースには表示されますが、管理パネルには表示されません。どうしたの?
アルニ

1
@Arni; 私の最初の推測は、インデックスの再作成が必要だということです:)
アレックスティマー

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とは何ですか?カスタム属性も追加できますか?
ジャファーピンジャー18

カスタム属性を設定するには?
ジャファーピンジャー

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);
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.