0

I would like to create a single abstract controller in which i will define my authorization code to check for user validity and want to inherit that controller in my other controllers, so that i don't need to write the same authentication code on every other controller.

0

You can simple include your controller in other controllers in which you want to inherit your controllers methods.

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Custom\Module\Controller\Adminhtml\Auth $auth
) {
    parent::__construct($context);
    $this->_auth = $auth;
}

Now if your controller has any function like login($username,$password)

public function login($username,$password)
    {
       /* ----------
        Code
       */
    }

In that case you can use this function in any controller where you have injected the controller like above like -

public function execute()
{
    //example
    $this->_auth->login($username,$pwd);
}
0

To follow Magento best practises, you would put your abstract controller into your module's Controller/ directory, and inherit in a subdirectory, for example Controller/Product/.

Magento's catalog module has an example for that:

vendor/magento/module-catalog/Controller/Product.php contains:

<?php

abstract class Product extends \Magento\Framework\App\Action\Action implements ViewInterface {
[...]

and vendor/magento/module-catalog/Controller/Product/View.php contains:

<?php

class View extends \Magento\Catalog\Controller\Product {
[...]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.