Magento – Magento 2.0 check if customer exists by name or number

apicustomermagento2

I updated my Magento to a newer version, now the old custom php code to check if a user exits by email does not work anymore

my old code

require_once '../app/Mage.php';

//first check if user with same email and number exists
function customerExists($email, $websiteId = null)
{
    $customer = Mage::getModel('customer/customer');
    if ($websiteId) {
        $customer->setWebsiteId($websiteId);
    }
    $customer->loadByEmail($email);
    if ($customer->getId()) {
        return $customer;
    }
    return false;
}

has stopped working can you please guide me how to make this work

Best Answer

try this

<?php

namespace yourNameSpace;

/**
 * Class yourclass
 *
 * @package yourNameSpace
 */
class yourclass
{
    /**
     * @var \Magento\Customer\Model\Customer
     */
    private $customer;

    /**
     * yourclass constructor.
     *
     * @param \Magento\Customer\Model\Customer $customer
     */
    public function __construct(\Magento\Customer\Model\Customer $customer)
    {
        $this->customer = $customer;
    }

    /**
     * @param string     $email
     * @param null $websiteId
     *
     * @return bool|\Magento\Customer\Model\Customer
     */
    public function customerExists($email, $websiteId = null)
    {
        $customer = $this->customer;
        if ($websiteId) {
            $customer->setWebsiteId($websiteId);
        }
        $customer->loadByEmail($email);
        if ($customer->getId()) {
            return $customer;
        }

        return false;
    }
}

This should work but if it doesn't just tell me so i can find an solution.

Related Topic