How to create a custom console command in Magento 2 – Rebuild URL Rewrite
Hi everybody, I am Cuong, Welcome back to my Magento 2 tutorial video series.
Today, I am going to show everybody a best practice, How to create a custom console command in Magento 2.
Before doing this practice, we take some minutes to learn the Magento CLI, how we can use it.
You can get it here
We can see it in the module named Magento_Catalog
In this practice, we will create a custom CLI command, that it allows rebuilding the product URL rewrites in the table named url_rewrite, you can find out this table in your database.
Okie, let’s go.
Let’s do this practice we only need to perform a few steps:
Step 1: Declaring a new module called PHPCuong_UrlRewrite
– Create the namespace PHPCuong in the path appcode.
– Create the module named UrlRewrite in the path appcodePHPCuong.
– Create the file named registration.php in the path appcodePHPCuongUrlRewrite
– Create the file named module.xml in the path appcodePHPCuongUrlRewriteetc
End of the step #1, I have been completed the step to create a new module called PHPCuong_UrlRewrite.
Step 2: Declaring the new CLI command
– Create the new file named di.xml in the path appcodePHPCuongUrlRewriteetc
Step 3: Create the new Command class
– Create the new file named ProductRebuildUrlRewrite.php in the path appcodePHPCuongUrlRewriteConsoleCommand
Step 4: Test and see results
Run the command lines:
php bin/magento setup:upgrade –keep-generated (Installing the new module)
php bin/magento cache:flush
php bin/magento list (Get the list of CLI commands in Magento 2)
php bin/magento catalog:product:urls:rebuild
Thank you for your watching. If you have any questions about this practice please feel free to leave a comment below.
Don’t forget to like, comment, share and subscribe to my channel for getting the latest videos.
Please do not hesitate to contact me if you need me to join your Magento project. My rate is $25/hour in Magento 1 and $30/hour in Magento 2.
Get the source codes of this tutorial in the Github