Làm cách nào để thêm một khách hàng lập trình trong Magento 2?


13

Tôi cần tạo một khách hàng theo chương trình trong Magento 2, tôi chưa tìm thấy nhiều tài liệu xung quanh ... về cơ bản những gì tôi cần làm là dịch đoạn mã sau thành "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();
}

Bạn muốn làm điều này trong một kịch bản độc lập, hoặc bạn có một mô hình hoặc một cái gì đó?
Marius

@Marius, tôi đã làm việc trên mô-đun này và tôi đã tạo ra một bộ điều khiển. Bộ điều khiển này tôi cần chuẩn bị một số dữ liệu để lưu và ý tưởng là gọi mô hình khách hàng và lưu thông tin đó. Đoạn mã trên có thể được đặt trong bộ điều khiển tôi muốn làm tương tự nhưng đối với Magento 2. Tôi vẫn hơi bối rối với cấu trúc mới của Magento 2 và bị mắc kẹt ở đây .. Tôi biết nó có liên quan đến việc tiêm lớp và các trường hợp đối tượng nhưng tôi không chắc làm thế nào để làm điều đó ...
Eduardo

Câu trả lời:


20

Được rồi, sau một thời gian tôi đã tìm thấy một giải pháp trong trường hợp người khác cần nó .. Magento sử dụng một cách tiếp cận khác để khởi tạo các đối tượng, cách truyền thống để khởi tạo các đối tượng trong Magento 1.x là sử dụng "Mage :: getModel (..)", điều này đã thay đổi trong Magento 2. Bây giờ Magento sử dụng trình quản lý đối tượng để khởi tạo các phản đối, tôi sẽ không nhập chi tiết về cách thức hoạt động của nó .. vì vậy, mã tương đương để tạo khách hàng trong Magento 2 sẽ như thế này:

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

Hy vọng đoạn mã này giúp người khác ..


6
Bạn đã rất thân thiết. Bạn nên tránh sử dụng objectManager trực tiếp bất cứ khi nào có thể - đó là hình thức xấu. Cách thích hợp để làm điều đó là sử dụng phép nội xạ phụ thuộc để lấy lớp 'nhà máy' và sử dụng phương thức đó để tạo một thể hiện. Nếu một lớp nhà máy không tồn tại cho một lớp nhất định, nó sẽ được tạo tự động. Tôi đã chỉnh sửa mã của bạn để sử dụng mã này (đã thêm nhà máy vào hàm tạo và lớp và gọi tạo ()) và tuân theo các tiêu chuẩn mã PSR-2.
Ryan Hoerr

Cảm ơn đã sửa @RyanH. Tôi đã nghĩ về việc sử dụng các lớp của nhà máy nhưng không chắc chắn làm thế nào, vì vậy tôi đã sử dụng objectManager ... Tôi sẽ đọc thêm về các tiêu chuẩn mã PSR-2 cho các dự án trong tương lai. Tôi đang sử dụng mã với các sửa chữa của bạn bây giờ và mọi thứ hoạt động hoàn hảo. Cảm ơn
Eduardo

@RyanH. Làm xong ; )
Eduardo

Tôi có thể thấy nó trong cơ sở dữ liệu nhưng không phải cho bảng quản trị. Chuyện gì đang xảy ra vậy?
Arni

1
@Arni; dự đoán đầu tiên của tôi là bạn cần reindex :)
Alex Timmer

4

Đây là cách đơn giản để tạo một khách hàng mới với nhóm mặc định và cửa hàng hiện tại.

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 ở đây là gì?, Chúng ta có thể thêm các thuộc tính tùy chỉnh không?
jafar pinjar

Làm cách nào để đặt thuộc tính tùy chỉnh?
jafar pinjar

0

Mã này chạy trong tệp bên ngoài hoặc tệp bảng điều khiển 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

Tất cả các ví dụ trên sẽ hoạt động, nhưng cách tiêu chuẩn phải luôn là sử dụng hợp đồng dịch vụ hơn các lớp cụ thể.

Do đó, các cách dưới đây nên được ưu tiên để tạo khách hàng theo chương trình.

                /** @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);
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.