Magento – Magento2 print customer full data array

customermagento2

How to print customer array full data.

public function __construct(
    \Magento\Customer\Model\Customer $customermodel,
    \Magento\Customer\Model\Address $addressmodel,
    \Magento\Customer\Api\CustomerRepositoryInterface $customer
)
{
    $this->_customer = $customer;
    $this->_address = $addressmodel;
    $this->_customermodel = $customermodel;
}
$customerData = $this->_customer->getById($customerId); 

How to print this $customerData ?

Best Answer

In Magento 1, any class which extended from Varien_Object had access to a method getData which would return the data property of the class as an array.

In Magento 2, there is no Varien_Object and no getData method. Data Models still have a data property, however, but it is of protected visibility and there is no accessor method for the whole array.

The only way to get at this property, then, is to use the __toArray method, in order to tell Magento to create an array representation of the data property.

This method is defined in \Magento\Framework\Api\AbstractSimpleObject, so you will only be able to use it if this class is in your model's inheritance tree.

<?php

// Inject your customer dependency in the usual way

/** @var $customer \Magento\Customer\Api\Data\CustomerInterface */
$customerData = $customer->__toArray();

var_dump($customerData);

// Outputs something like:

array(22) {
  'website_id' =>
  string(1) "1"
  'email' =>
  string(34) "me@example.com"
  'group_id' =>
  string(2) "17"
  'store_id' =>
  string(1) "1"
  'created_at' =>
  string(19) "2018-04-06 15:52:34"
  'updated_at' =>
  string(19) "2018-06-26 13:42:09"
  'disable_auto_group_change' =>
  string(1) "0"
  'created_in' =>
  string(18) "Default Store View"

  ...Output truncated

A word of warning before copy-pasting the above, however: The code snippet above depends on whether your Customer Data Model also extends from \Magento\Framework\Api\AbstractSimpleObject.

The default, as defined in vendor/magento/module-customer/etc/di.xml specifies \Magento\Customer\Model\Data\Customer as the concrete implementation, which does include \Magento\Framework\Api\AbstractSimpleObject in it's inheritance tree, which is why the code snippet above works.

Related Topic