Magento 2 – How to Create First Custom Module and Observer

event-observermagento2module

this is my first project with Magento and my first question here. I'm trying to create an Observer, but I can't figure it out.

The error in var/log/system.log is: main.CRITICAL: Exception message: Class Campaign\CampaignCustomer\Observer\CustomerRegisterSuccess does not exist

Here's my folder structure:
enter image description here

[etc] folder contains these 2 files:

events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="customer_save_before">
        <observer name="obs_customer_account_before" instance="Campaign\CampaignCustomer\Observer\CustomerRegisterSuccess" shared="false" />
    </event>
</config>

module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Campaign_CampaignCustomer" setup_version="2.0.0" />
</config>

I've run the following commands in my terminal and everything looks fine:

php bin/magento module:enable Campaign_CampaignCustomer
php bin/magento setup:upgrade
php bin/magento cache:clean
php bin/magento cache:flush

The registration.php file looks like this:

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Campaign_CampaignCustomer',
    __DIR__
);

And finally, my CustomRegisterSuccess class:

<?php

namespace Campaign\CampaignCustomer\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Magento\Customer\Api\CustomerRepositoryInterface;

class CustomerRegisterSuccess implements ObserverInterface
{
    /** @var CustomerRepositoryInterface */
    protected $customerRepository;

    /**
     * @param CustomerRepositoryInterface $customerRepository
     */
    public function __construct(
        CustomerRepositoryInterface $customerRepository
    ) {
        $this->customerRepository = $customerRepository;
    }

    /**
     * Manages redirect
     */
    public function execute(Observer $observer)
    {

        $accountController = $observer->getAccountController();
        $customer = $observer->getCustomer();
        $request = $accountController->getRequest();
        $customer_number = $request->getParam('customer_number');
        $customer->setCustomAttribute('customer_number', $customer_number);
        $this->customerRepository->save($customer);
    }
}

What's wrong with my code? Please help.

Best Answer

And finally, my CustomRegisterSuccess class:

CustomRegisterSuccess

Change CustomRegisterSuccess to CustomerRegisterSuccess and you will be fine.

Cheers.