Bagaimana cara menambahkan pelanggan secara terprogram di Magento 2?


13

Saya perlu membuat pelanggan secara terprogram di Magento 2, saya belum menemukan banyak dokumentasi di sekitar ... pada dasarnya yang perlu saya lakukan adalah menerjemahkan kode berikut ke "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();
}

Anda ingin melakukan ini dalam skrip mandiri, atau Anda memiliki model atau sesuatu?
Marius

@Marius, saya telah mengerjakan modul ini dan saya telah membuat controller. Jika pengontrol ini saya perlu menyiapkan beberapa data untuk disimpan dan idenya adalah memanggil model pelanggan dan menyimpan informasi itu. Kode di atas dapat ditempatkan di controller saya ingin melakukan hal yang sama tetapi untuk Magento 2. Saya masih agak bingung dengan struktur baru Magento 2 dan terjebak di sini sekarang .. Saya tahu Ini ada hubungannya dengan suntikan kelas dan objek contoh tapi saya tidak yakin bagaimana melakukannya ...
Eduardo

Jawaban:


20

Oke, setelah beberapa saat saya menemukan solusi kalau-kalau orang lain membutuhkannya .. Magento menggunakan pendekatan lain untuk instantiate objek, cara tradisional untuk instantiate objek di Magento 1.x menggunakan "Mage :: getModel (..)", ini telah berubah di Magento 2. Sekarang Magento menggunakan manajer objek untuk membuat instance objek, saya tidak akan memasukkan detail tentang cara kerjanya .. jadi, kode yang setara untuk membuat pelanggan di Magento 2 akan terlihat seperti ini:

<?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();
    }
}

Semoga cuplikan kode ini membantu orang lain ..


6
Anda sangat dekat. Anda harus menghindari penggunaan objectManager secara langsung bila memungkinkan - ini adalah bentuk yang buruk. Cara yang tepat untuk melakukannya adalah menggunakan injeksi ketergantungan untuk mendapatkan kelas 'pabrik', dan menggunakannya untuk membuat instance. Jika kelas pabrik tidak ada untuk kelas yang diberikan, itu akan dihasilkan secara otomatis. Saya telah mengedit kode Anda untuk menggunakan ini (menambahkan pabrik ke konstruktor dan kelas, dan memanggil create ()), dan ikuti standar kode PSR-2.
Ryan Hoerr

Terima kasih atas koreksi @RyanH. Saya berpikir tentang menggunakan kelas pabrik tetapi tidak yakin bagaimana caranya, jadi saya menggunakan objectManager ... Saya akan membaca lebih lanjut tentang standar kode PSR-2 untuk proyek masa depan. Saya menggunakan kode dengan koreksi Anda sekarang dan semuanya berfungsi dengan baik. Terima kasih
Eduardo

@RyanH. Dilakukan; )
Eduardo

Saya bisa melihatnya di database tetapi tidak untuk panel Admin. Apa yang terjadi?
Arni

1
@Arni; Dugaan pertama saya adalah bahwa Anda harus mengindeks ulang :)
Alex Timmer

4

Berikut adalah cara sederhana untuk membuat pelanggan baru dengan grup default dan toko saat ini.

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

Apa itu $ request di sini ?, bisakah kita menambahkan atribut khusus juga?
jafar pinjar

Bagaimana cara mengatur atribut khusus?
jafar pinjar

0

Kode ini dijalankan dalam file eksternal atau file konsol 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

Semua contoh di atas akan bekerja, tetapi cara standar harus selalu menggunakan kontrak layanan daripada kelas konkret.

Oleh karena itu, cara di bawah ini harus lebih disukai untuk menciptakan pelanggan secara terprogram.

                /** @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);
Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.