In Magento 2, to add a new action to a pre-existing route without interfering with the existing functionality, the new action should be placed in the same directory structure under the new module’s controller namespace. Magento's autoloading mechanism will automatically detect and include it alongside the original module's actions.
Here's how you can achieve this:
Directory Structure: Ensure that your new module's controller directory structure mirrors that of the original module.
Controller Action: Define the new action within the appropriate directory.
For example, if you want to add a new action to the catalog route in Magento_Catalog:
Create a directory structure app/code/My/Module/Controller/Catalog/.
Add your new action class in this directory, for example:
namespace My\Module\Controller\Catalog;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
class NewAction extends Action
{
public function __construct(Context $context)
{
parent::__construct($context);
}
public function execute()
{
// Your custom logic here
}
}
Router Configuration: Magento automatically includes this action when the route matches.
By following this method, you ensure that your new action is added seamlessly without modifying the original module or causing conflicts. Magento's router will include and recognize your action based on the directory and namespace conventions.
Sources:
Fundamentals of Magento 2 Development documents .
Magento 2 official developer documentation.