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

답변:


20

마 젠토는 다른 방법으로 객체를 인스턴스화하는 또 다른 방법을 사용합니다. Magento 1.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를 직접 사용하지 마십시오. 형식이 잘못되었습니다. 올바른 방법은 의존성 주입을 사용하여 'factory'클래스를 얻고 인스턴스를 만드는 데 사용하는 것입니다. 지정된 클래스에 팩토리 클래스가 존재하지 않으면 자동 생성됩니다. 이 코드를 사용하도록 코드를 편집하고 (제조자와 클래스에 팩토리를 추가하고 create () 호출) PSR-2 코드 표준을 따릅니다.
Ryan Hoerr

@RyanH 수정 해 주셔서 감사합니다. 팩토리 클래스 사용에 대해 생각했지만 방법을 잘 모르겠으므로 objectManager를 사용했습니다. 향후 프로젝트를위한 PSR-2 코드 표준에 대해 자세히 읽어 볼 것입니다. 나는 지금 당신의 정정과 함께 코드를 사용하고 있으며 모든 것이 완벽하게 작동합니다. 감사합니다
Eduardo

@RyanH. 완료; )
Eduardo Eduardo

데이터베이스에서는 볼 수 있지만 관리자 패널에서는 볼 수 없습니다. 무슨 일이 일어난거야?
Arni

1
@ 아르 니; 내 첫 번째 추측은 당신이 다시 색인을 생성해야한다는 것입니다 :)
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);
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.