W poprzednich postach dotyczących Magento 2 pisałem o przesłanianiu szablonów. Jeśli nie znasz jeszcze tych zagadnień to odwiedź poniższe linki:
- NADPISYWANIE SZABLONÓW ADMINA PRZY UŻYCIU WŁASNEGO MODUŁU
- NADPISYWANIE SZABLONÓW MAGENTO WE WŁASNYM MOTYWIE
Teraz czas na nadpisywanie klas. Wiedz, że nie jest to trudne. Standardowy sposób, który opiszę na przykładzie kontrolera, równie dobrze sprawdzi się w nadpisywaniu modeli, bloków, klas pomocniczych, czyli helperów itd.
Nadpisywanie klas stosujemy w sytuacji, kiedy chcemy rozszerzyć jakieś funkcjonalności lub dodać nowe. Oczywiście nie możemy tego zrobić w vendorze, bo przy jakiejkolwiek aktualizacji systemu, utracimy wprowadzone zmiany i będziemy musieli je ponownie wdrażać. To nie jest dobra praktyka. W takiej sytuacji trzeba skorzystać z przesłaniania i nadpisać odpowiednią klasę lub klasy.
PRZYKŁAD
W poniższym przykładzie nadpiszę klasę kontrolera: CreatePost.php, która obsługuje m.in. przekierowania na odpowiednią stronę po założeniu konta. Do pliku wprowadzę minimalną poprawkę, która wyłączy automatyczne logowanie do konta po prawidłowym zarejestrowaniu się.
1. Tworzymy nowy moduł. W tym celu zapisujemy dwa pliki w lokalizacji:
- app/code/Geek/Customer/registration.php
- app/code/Geek/Customer/etc/module.xml
gdzie Geek/Customer – to przykładowa nazwa przestrzeni nazw / nazwa modułu, z których będziemy korzystać w poszczególnych plikach.
Rejestrujemy moduł w registration.php:
1 2 3 4 5 6 7 |
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Geek_Customer', __DIR__ ); |
Zapisujemy konfiguracje w module.xml:
1 2 3 4 5 6 7 |
<?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="Geek_Customer" setup_version="1.0.0" /> <sequence> <module name="Magento_Customer"/> </sequence> </config> |
2. Tworzymy plik di.xml (etc/di.xml). W tym pliku konfigurujemy zależności, które są wstrzykiwane przez menadżer obiektów (object manager). Korzystając z preferencji, w parametrze for wskazujemy adres do klasy, która zostanie nadpisana (vendor/magento/module-customer/Controller/Account/CreatePost.php). Natomiast type wskazuje nową lokalizację pliku, w naszym module (app/code/Geek/Customer/Controller/Account/CreatePost.php).
1 2 3 4 5 6 7 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="Magento\Customer\Controller\Account\CreatePost" type="Geek\Customer\Controller\Account\CreatePost" /> </config> |
3. Kopiujemy plik CreatePost.php z vendora do modułu.
Aktualizujemy w nim przestrzeń nazw:
1 |
namespace Geek\Customer\Controller\Account; |
oraz usuwamy lub komentujemy zapis (w linii 379):
1 |
$this->session->setCustomerDataAsLoggedIn($customer); |
Poniżej kod całej klasy po zmianach:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 |
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Geek\Customer\Controller\Account; use Magento\Customer\Api\CustomerRepositoryInterface as CustomerRepository; use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface; use Magento\Customer\Model\Account\Redirect as AccountRedirect; use Magento\Customer\Api\Data\AddressInterface; use Magento\Framework\Api\DataObjectHelper; use Magento\Framework\App\Action\Context; use Magento\Customer\Model\Session; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\CsrfAwareActionInterface; use Magento\Framework\App\ObjectManager; use Magento\Framework\App\Request\InvalidRequestException; use Magento\Framework\App\RequestInterface; use Magento\Framework\Controller\Result\Redirect; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Phrase; use Magento\Store\Model\StoreManagerInterface; use Magento\Customer\Api\AccountManagementInterface; use Magento\Customer\Helper\Address; use Magento\Framework\UrlFactory; use Magento\Customer\Model\Metadata\FormFactory; use Magento\Newsletter\Model\SubscriberFactory; use Magento\Customer\Api\Data\RegionInterfaceFactory; use Magento\Customer\Api\Data\AddressInterfaceFactory; use Magento\Customer\Api\Data\CustomerInterfaceFactory; use Magento\Customer\Model\Url as CustomerUrl; use Magento\Customer\Model\Registration; use Magento\Framework\Escaper; use Magento\Customer\Model\CustomerExtractor; use Magento\Framework\Exception\StateException; use Magento\Framework\Exception\InputException; use Magento\Framework\Data\Form\FormKey\Validator; use Magento\Customer\Controller\AbstractAccount; /** * Post create customer action * * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class CreatePost extends AbstractAccount implements CsrfAwareActionInterface, HttpPostActionInterface { /** * @var \Magento\Customer\Api\AccountManagementInterface */ protected $accountManagement; /** * @var \Magento\Customer\Helper\Address */ protected $addressHelper; /** * @var \Magento\Customer\Model\Metadata\FormFactory */ protected $formFactory; /** * @var \Magento\Newsletter\Model\SubscriberFactory */ protected $subscriberFactory; /** * @var \Magento\Customer\Api\Data\RegionInterfaceFactory */ protected $regionDataFactory; /** * @var \Magento\Customer\Api\Data\AddressInterfaceFactory */ protected $addressDataFactory; /** * @var \Magento\Customer\Model\Registration */ protected $registration; /** * @var \Magento\Customer\Api\Data\CustomerInterfaceFactory */ protected $customerDataFactory; /** * @var \Magento\Customer\Model\Url */ protected $customerUrl; /** * @var \Magento\Framework\Escaper */ protected $escaper; /** * @var \Magento\Customer\Model\CustomerExtractor */ protected $customerExtractor; /** * @var \Magento\Framework\UrlInterface */ protected $urlModel; /** * @var \Magento\Framework\Api\DataObjectHelper */ protected $dataObjectHelper; /** * @var Session */ protected $session; /** * @var AccountRedirect */ private $accountRedirect; /** * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory */ private $cookieMetadataFactory; /** * @var \Magento\Framework\Stdlib\Cookie\PhpCookieManager */ private $cookieMetadataManager; /** * @var Validator */ private $formKeyValidator; /** * @var CustomerRepository */ private $customerRepository; /** * @param Context $context * @param Session $customerSession * @param ScopeConfigInterface $scopeConfig * @param StoreManagerInterface $storeManager * @param AccountManagementInterface $accountManagement * @param Address $addressHelper * @param UrlFactory $urlFactory * @param FormFactory $formFactory * @param SubscriberFactory $subscriberFactory * @param RegionInterfaceFactory $regionDataFactory * @param AddressInterfaceFactory $addressDataFactory * @param CustomerInterfaceFactory $customerDataFactory * @param CustomerUrl $customerUrl * @param Registration $registration * @param Escaper $escaper * @param CustomerExtractor $customerExtractor * @param DataObjectHelper $dataObjectHelper * @param AccountRedirect $accountRedirect * @param CustomerRepository $customerRepository * @param Validator $formKeyValidator * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( Context $context, Session $customerSession, ScopeConfigInterface $scopeConfig, StoreManagerInterface $storeManager, AccountManagementInterface $accountManagement, Address $addressHelper, UrlFactory $urlFactory, FormFactory $formFactory, SubscriberFactory $subscriberFactory, RegionInterfaceFactory $regionDataFactory, AddressInterfaceFactory $addressDataFactory, CustomerInterfaceFactory $customerDataFactory, CustomerUrl $customerUrl, Registration $registration, Escaper $escaper, CustomerExtractor $customerExtractor, DataObjectHelper $dataObjectHelper, AccountRedirect $accountRedirect, CustomerRepository $customerRepository, Validator $formKeyValidator = null ) { $this->session = $customerSession; $this->scopeConfig = $scopeConfig; $this->storeManager = $storeManager; $this->accountManagement = $accountManagement; $this->addressHelper = $addressHelper; $this->formFactory = $formFactory; $this->subscriberFactory = $subscriberFactory; $this->regionDataFactory = $regionDataFactory; $this->addressDataFactory = $addressDataFactory; $this->customerDataFactory = $customerDataFactory; $this->customerUrl = $customerUrl; $this->registration = $registration; $this->escaper = $escaper; $this->customerExtractor = $customerExtractor; $this->urlModel = $urlFactory->create(); $this->dataObjectHelper = $dataObjectHelper; $this->accountRedirect = $accountRedirect; $this->formKeyValidator = $formKeyValidator ?: ObjectManager::getInstance()->get(Validator::class); $this->customerRepository = $customerRepository; parent::__construct($context); } /** * Retrieve cookie manager * * @deprecated 100.1.0 * @return \Magento\Framework\Stdlib\Cookie\PhpCookieManager */ private function getCookieManager() { if (!$this->cookieMetadataManager) { $this->cookieMetadataManager = ObjectManager::getInstance()->get( \Magento\Framework\Stdlib\Cookie\PhpCookieManager::class ); } return $this->cookieMetadataManager; } /** * Retrieve cookie metadata factory * * @deprecated 100.1.0 * @return \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory */ private function getCookieMetadataFactory() { if (!$this->cookieMetadataFactory) { $this->cookieMetadataFactory = ObjectManager::getInstance()->get( \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::class ); } return $this->cookieMetadataFactory; } /** * Add address to customer during create account * * @return AddressInterface|null */ protected function extractAddress() { if (!$this->getRequest()->getPost('create_address')) { return null; } $addressForm = $this->formFactory->create('customer_address', 'customer_register_address'); $allowedAttributes = $addressForm->getAllowedAttributes(); $addressData = []; $regionDataObject = $this->regionDataFactory->create(); foreach ($allowedAttributes as $attribute) { $attributeCode = $attribute->getAttributeCode(); $value = $this->getRequest()->getParam($attributeCode); if ($value === null) { continue; } switch ($attributeCode) { case 'region_id': $regionDataObject->setRegionId($value); break; case 'region': $regionDataObject->setRegion($value); break; default: $addressData[$attributeCode] = $value; } } $addressDataObject = $this->addressDataFactory->create(); $this->dataObjectHelper->populateWithArray( $addressDataObject, $addressData, \Magento\Customer\Api\Data\AddressInterface::class ); $addressDataObject->setRegion($regionDataObject); $addressDataObject->setIsDefaultBilling( $this->getRequest()->getParam('default_billing', false) )->setIsDefaultShipping( $this->getRequest()->getParam('default_shipping', false) ); return $addressDataObject; } /** * @inheritDoc */ public function createCsrfValidationException( RequestInterface $request ): ?InvalidRequestException { /** @var Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $url = $this->urlModel->getUrl('*/*/create', ['_secure' => true]); $resultRedirect->setUrl($this->_redirect->error($url)); return new InvalidRequestException( $resultRedirect, [new Phrase('Invalid Form Key. Please refresh the page.')] ); } /** * @inheritDoc */ public function validateForCsrf(RequestInterface $request): ?bool { return null; } /** * Create customer account action * * @return void * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function execute() { /** @var Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); if ($this->session->isLoggedIn() || !$this->registration->isAllowed()) { $resultRedirect->setPath('*/*/'); return $resultRedirect; } if (!$this->getRequest()->isPost() || !$this->formKeyValidator->validate($this->getRequest()) ) { $url = $this->urlModel->getUrl('*/*/create', ['_secure' => true]); return $this->resultRedirectFactory->create() ->setUrl($this->_redirect->error($url)); } $this->session->regenerateId(); try { $address = $this->extractAddress(); $addresses = $address === null ? [] : [$address]; $customer = $this->customerExtractor->extract('customer_account_create', $this->_request); $customer->setAddresses($addresses); $password = $this->getRequest()->getParam('password'); $confirmation = $this->getRequest()->getParam('password_confirmation'); $redirectUrl = $this->session->getBeforeAuthUrl(); $this->checkPasswordConfirmation($password, $confirmation); $customer = $this->accountManagement ->createAccount($customer, $password, $redirectUrl); if ($this->getRequest()->getParam('is_subscribed', false)) { $extensionAttributes = $customer->getExtensionAttributes(); $extensionAttributes->setIsSubscribed(true); $customer->setExtensionAttributes($extensionAttributes); $this->customerRepository->save($customer); } $this->_eventManager->dispatch( 'customer_register_success', ['account_controller' => $this, 'customer' => $customer] ); $confirmationStatus = $this->accountManagement->getConfirmationStatus($customer->getId()); if ($confirmationStatus === AccountManagementInterface::ACCOUNT_CONFIRMATION_REQUIRED) { $email = $this->customerUrl->getEmailConfirmationUrl($customer->getEmail()); // @codingStandardsIgnoreStart $this->messageManager->addSuccess( __( 'You must confirm your account. Please check your email for the confirmation link or <a href="%1">click here</a> for a new link.', $email ) ); // @codingStandardsIgnoreEnd $url = $this->urlModel->getUrl('*/*/index', ['_secure' => true]); $resultRedirect->setUrl($this->_redirect->success($url)); } else { //$this->session->setCustomerDataAsLoggedIn($customer); $this->messageManager->addSuccess($this->getSuccessMessage()); $requestedRedirect = $this->accountRedirect->getRedirectCookie(); if (!$this->scopeConfig->getValue('customer/startup/redirect_dashboard') && $requestedRedirect) { $resultRedirect->setUrl($this->_redirect->success($requestedRedirect)); $this->accountRedirect->clearRedirectCookie(); return $resultRedirect; } $resultRedirect = $this->accountRedirect->getRedirect(); } if ($this->getCookieManager()->getCookie('mage-cache-sessid')) { $metadata = $this->getCookieMetadataFactory()->createCookieMetadata(); $metadata->setPath('/'); $this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata); } return $resultRedirect; } catch (StateException $e) { $url = $this->urlModel->getUrl('customer/account/forgotpassword'); // @codingStandardsIgnoreStart $message = __( 'There is already an account with this email address. If you are sure that it is your email address, <a href="%1">click here</a> to get your password and access your account.', $url ); // @codingStandardsIgnoreEnd $this->messageManager->addError($message); } catch (InputException $e) { $this->messageManager->addError($this->escaper->escapeHtml($e->getMessage())); foreach ($e->getErrors() as $error) { $this->messageManager->addError($this->escaper->escapeHtml($error->getMessage())); } } catch (LocalizedException $e) { $this->messageManager->addError($this->escaper->escapeHtml($e->getMessage())); } catch (\Exception $e) { $this->messageManager->addException($e, __('We can\'t save the customer.')); } $this->session->setCustomerFormData($this->getRequest()->getPostValue()); $defaultUrl = $this->urlModel->getUrl('*/*/create', ['_secure' => true]); return $resultRedirect->setUrl($this->_redirect->error($defaultUrl)); } /** * Make sure that password and password confirmation matched * * @param string $password * @param string $confirmation * @return void * @throws InputException */ protected function checkPasswordConfirmation($password, $confirmation) { if ($password != $confirmation) { throw new InputException(__('Please make sure your passwords match.')); } } /** * Retrieve success message * * @return string */ protected function getSuccessMessage() { if ($this->addressHelper->isVatValidationEnabled()) { if ($this->addressHelper->getTaxCalculationAddressType() == Address::TYPE_SHIPPING) { // @codingStandardsIgnoreStart $message = __( 'If you are a registered VAT customer, please <a href="%1">click here</a> to enter your shipping address for proper VAT calculation.', $this->urlModel->getUrl('customer/address/edit') ); // @codingStandardsIgnoreEnd } else { // @codingStandardsIgnoreStart $message = __( 'If you are a registered VAT customer, please <a href="%1">click here</a> to enter your billing address for proper VAT calculation.', $this->urlModel->getUrl('customer/address/edit') ); // @codingStandardsIgnoreEnd } } else { $message = __('Thank you for registering with %1.', $this->storeManager->getStore()->getFrontendName()); } return $message; } } |
Oczywiście klasę możesz rozszerzać o własne funkcjonalności.
I to wszystko w temacie 🙂
Do następnego =>