What is difference between MAGE_RUN_TYPE: store and website ?

The MAGE_RUN_TYPE parameter in Magento specifies the scope of the store switch that is being requested. There are two possible values for MAGE_RUN_TYPE: store and website.

When MAGE_RUN_TYPE is set to store, Magento will switch the current store view to a different store view within the same website. In this case, the MAGE_RUN_CODE parameter should be set to the code of the target store view.

When MAGE_RUN_TYPE is set to website, Magento will switch the current website to a different website. In this case, the MAGE_RUN_CODE parameter should be set to the code of the target website.

So the main difference between store and website is the scope of the switch. If you want to switch between store views within the same website, you should use store, and if you want to switch between different websites, you should use website.

Here’s an example to help illustrate the difference:

Suppose you have two websites set up in Magento, website1 and website2, each with two store views: storeview1 and storeview2. If you want to switch from storeview1 in website1 to storeview2 in website1, you should set MAGE_RUN_TYPE to store, and set MAGE_RUN_CODE to storeview2. If you want to switch from storeview1 in website1 to storeview1 in website2, you should set MAGE_RUN_TYPE to website, and set MAGE_RUN_CODE to website2.

Magento Framework Flow – Basic

Controller

The Controllers are located in the Controller folder of a module, and are organized into subfolders based on the module’s front-end or admin area. For example, a controller for the front-end would be located at app/code/{Vendor}/{Module}/Controller/{ActionFolder}/{ControllerName}.php.

A Few Classes and Interfaces usually that the Controller Class extends or implements

Magento\Framework\App\Action\Action: This is the base class for front-end controllers. It provides basic functionality for processing incoming requests, such as retrieving request parameters, handling exceptions, and generating responses.

Magento\Backend\App\Action: This is the base class for admin controllers. It provides functionality specific to the admin area, such as handling ACL permissions and displaying admin-specific UI elements.

Magento\Framework\App\Action\HttpGetActionInterface: This interface defines the execute() method for controllers that handle GET requests.

Magento\Framework\App\Action\HttpPostActionInterface: This interface defines the execute() method for controllers that handle POST requests.

Magento\Framework\App\Action\HttpPutActionInterface: This interface defines the execute() method for controllers that handle PUT requests.

Magento\Framework\App\Action\HttpDeleteActionInterface: This interface defines the execute() method for controllers that handle DELETE requests.

Magento\Framework\App\Action\Context: This class provides access to various resources that are commonly used in controllers, such as the request object, response object, and session object.

Magento\Framework\Controller\ResultFactory: This class provides a convenient way to create response objects of various types, such as JSON, XML, or HTML.

Magento\Framework\Message\ManagerInterface: This interface provides a way to add messages to the session, which can be used to display success or error messages to the user.

Action

The Actions are located in the Controller/{ActionFolder} folder of a module, and are organized into subfolders based on the module’s front-end or admin area. For example, an action for the front-end would be located at app/code/{Vendor}/{Module}/Controller/{ActionFolder}/{ActionName}.php.

A Few Classes and Interfaces usually that the Actions Class extends or implements

Magento\Framework\App\RequestInterface: This interface provides methods for retrieving data from the incoming request, such as request parameters or headers.

Magento\Framework\App\ResponseInterface: This interface provides methods for generating a response to send back to the client, such as setting the response code or headers.

Magento\Framework\App\Action\Context: This class provides access to various resources that are commonly used in actions, such as the request object, response object, and session object.

Magento\Framework\Controller\ResultFactory: This class provides a convenient way to create response objects of various types, such as JSON, XML, or HTML.

Magento\Framework\Message\ManagerInterface: This interface provides a way to add messages to the session, which can be used to display success or error messages to the user.

Service

The Services are typically located in the Model folder of a module, and are organized into subfolders based on the module’s front-end or admin area. For example, a service for the front-end would be located at app/code/{Vendor}/{Module}/Model/{ServiceFolder}/{ServiceName}.php.

A Few Classes and Interfaces usually that the Service Class extends or implements

Magento\Framework\Model\AbstractModel: This class provides basic functionality for interacting with the database, such as saving or deleting records.

Magento\Framework\Api\SearchCriteriaInterface: This interface provides a way to specify criteria for searching the database, such as filtering or sorting.

Magento\Framework\Api\SearchResultsInterface: This interface provides a way to return the results of a database search, such as a list of records that match a certain set of criteria.

Magento\Framework\Api\DataObjectHelper: This class provides methods for converting data between arrays and objects, which can be useful for working with database records.

Magento\Framework\Api\ExtensibleDataObjectConverter: This class provides methods for converting between database records and objects that implement the Magento\Framework\Api\ExtensionAttributesInterface interface, which can be used to store additional data associated with an object.

Magento\Framework\Api\SearchCriteriaBuilder: This class provides a fluent interface for building search criteria objects.

Model

The Models are located in the Model folder of a module, and are organized into subfolders based on the module’s front-end or admin area. For example, a model for the front-end would be located at app/code/{Vendor}/{Module}/Model/{ModelFolder}/{ModelName}.php.

A Few Classes and Interfaces usually that the Model Classes extends or implements

Magento\Framework\Model\AbstractModel: This class provides basic functionality for interacting with the database, such as saving or deleting records.

Magento\Framework\DataObject: This class provides a generic data object that can hold arbitrary data.

Magento\Framework\Model\ResourceModel\Db\AbstractDb: This class provides basic functionality for interacting with the database, such as executing queries or preparing statements.

Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection: This class provides a way to represent a collection of database records, and includes methods for filtering, sorting, and paging through the collection.

Magento\Framework\Api\CustomAttributesDataInterface: This interface can be implemented by model classes to add support for custom attributes, which are additional data fields that can be associated with an entity.

Magento\Framework\Api\SearchResultsInterface: This interface can be implemented by model classes to provide a way to return the results of a database search, such as a list of records that match a certain set of criteria.

Resource Model

The Resource Models are typically located in the Model/ResourceModel folder of a module, and are organized into subfolders based on the module’s front-end or admin area. For example, a resource model for the front-end would be located at app/code/{Vendor}/{Module}/Model/ResourceModel/{ResourceModelFolder}/{ResourceModelName}.php.

A Few Classes and Interfaces usually that the Resource Model Classes extends or implements

Magento\Framework\Model\ResourceModel\Db\AbstractDb: This class provides basic functionality for interacting with the database, such as executing queries or preparing statements.

Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection: This class provides a way to represent a collection of database records, and includes methods for filtering, sorting, and paging through the collection.

Magento\Framework\Model\ResourceModel\Db\AbstractVersionControl: This class provides functionality for version control of database records, including creating new versions, comparing versions, and restoring previous versions.

Magento\Framework\EntityManager\MetadataPool: This class provides access to the metadata for database tables and fields, allowing resource model classes to interact with the database schema in a flexible and dynamic way.

Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface: This interface can be used to add support for custom attributes to resource model classes, which are additional data fields that can be associated with a database record.

View Model

The View Models are typically located in the ViewModel folder of a module, and are organized into subfolders based on the module’s front-end or admin area. For example, a view model for the front-end would be located at app/code/{Vendor}/{Module}/ViewModel/{ViewModelFolder}/{ViewModelName}.php.

A Few Classes and Interfaces usually that the Resource Model Classes extends or implements

Magento\Framework\View\Element\Block\ArgumentInterface: Defines a method getData which returns data to be passed to the view template. This interface is implemented by view model classes to provide data to the block.

Magento\Framework\View\Element\Block\ArgumentInterface: Defines a method getData which returns data to be passed to the view template. This interface is implemented by view model classes to provide data to the block.

Magento\Framework\View\Element\Block\ArgumentInterface: Defines a method getData which returns data to be passed to the view template. This interface is implemented by view model classes to provide data to the block.

Magento\Framework\View\Element\Block\ArgumentInterface: Defines a method getData which returns data to be passed to the view template. This interface is implemented by view model classes to provide data to the block.

Magento\Framework\View\Element\Block\ArgumentInterface: Defines a method getData which returns data to be passed to the view template. This interface is implemented by view model classes to provide data to the block.

Block

The Blocks are typically located in the Block folder of a module, and are organized into subfolders based on the module’s front-end or admin area. For example, a block for the front-end would be located at app/code/{Vendor}/{Module}/Block/{BlockFolder}/{BlockName}.php.

A Few Classes and Interfaces usually that the Block Classes extends or implements

Magento\Framework\View\Element\AbstractBlock: This is the base class for all block classes in Magento 2. It provides a number of useful methods for managing the block's layout and child blocks, as well as rendering the block's HTML output.

Magento\Framework\View\Element\Template: This class provides additional functionality for rendering templates using the Magento layout system. It defines methods for accessing layout handles and retrieving templates for specific blocks.

Magento\Framework\View\Element\Block\ArgumentInterface: This interface defines a method getData which returns data to be passed to the block's template. This interface is often implemented by view model classes that provide data to the block.

Magento\Framework\DataObject: This class provides a simple object-oriented interface for managing data. Block classes can extend this class to provide additional data and functionality.

Magento\Framework\View\Element\BlockInterface: This interface defines a number of methods that all block classes must implement. These methods include toHtml for rendering the block's HTML output, getCacheKeyInfo for determining the cache key for the block, and getCacheLifetime for determining the cache lifetime of the block.

View

The Views are located in the view folder of a module, and are organized into subfolders based on the module’s front-end or admin area. For example, a view for the front-end would be located at app/code/{Vendor}/{Module}/view/{Area}/{ActionFolder}/{TemplateFile}.phtml.

Create a new module with API Calling in Magento 2

app\code\Leela\Starwars\registration.php

<?php

use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Leela_Starwars', __DIR__);

app\code\Leela\Starwars\etc\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="Leela_Starwars">
    
    </module>
</config>

app\code\Leela\Starwars\Controller\Index\Index.php

<?php
namespace Leela\Starwars\Controller\Index;
use \Magento\Framework\App\Action\HttpGetActionInterface;
use \Magento\Framework\View\Result\PageFactory;

class Index implements HttpGetActionInterface 
{
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

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

    /**
     * Prints the information 
     * @return Page
     */
    public function execute()
    {
        return $this->resultPageFactory->create();
    }
}

app\code\Leela\Starwars\view\frontend\layout\starwars_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
    <title>Leela - Starwars</title>
</head>
<body>
    <referenceContainer name="content">
        <block class="Leela\Starwars\Block\StarWarsMainAPI"
            name="starwarsData"
                template="Leela_Starwars::api.phtml" />
    </referenceContainer>
</body>
</page>

app\code\Leela\Starwars\view\frontend\templates\api.phtml

<h2><?php echo 'This is my first module'; ?></h2>
<h2><?php echo $block->getStarWarHeros(); ?></h2>

app\code\Leela\Starwars\Block\StarWarsMainAPI.php

<?php

namespace Leela\Starwars\Block;
use \Magento\Framework\View\Element\Template;

class StarWarsMainAPI extends Template
{

public function __construct (
    \Magento\Backend\Block\Template\Context $context,
    array $data = []
){
    parent::__construct($context,$data);
}

public function getStarWarHeros()
{
    // Call the Star Wars API to retrieve a list of characters
$characters = $this->callStarWarsAPI('people/');
$result ='';
// If the API call was successful, loop through the character data and display their names
if ($characters !== false) {
    foreach ($characters['results'] as $character) {
        $result .= $character['name'] . '<br>';
    }
    return $result;
} else {
    return 'Error: could not retrieve character data.';
}
   
}


public function callStarWarsAPI($endpoint, $params = []) {
    // Set the base URL for the Star Wars API
    $baseUrl = 'https://swapi.dev/api/';

    // Initialize a new cURL resource
    $curl = curl_init();

    // Build the full URL for the API request
    $url = $baseUrl . $endpoint;

    // If there are any query parameters, append them to the URL
    if (!empty($params)) {
        $url .= '?' . http_build_query($params);
    }

    // Set the cURL options
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
    ]);

    // Execute the cURL request
    $response = curl_exec($curl);

    // If there was an error with the cURL request, return false
    if ($response === false) {
        return false;
    }

    // Convert the JSON response to an array
    $data = json_decode($response, true);

    // If there was an error with the API request, return false
    if (isset($data['detail'])) {
        return false;
    }

    // Close the cURL resource
    curl_close($curl);

    // Return the response data as an array
    return $data;
}

}



?>

app\code\Leela\Starwars\etc\frontend\routes.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="starwars" frontName="starwars">
            <module name="Leela_Starwars" />
        </route>
    </router>
</config>


php bin/magento setup:upgrade
php bin/magento setip:static-content:deploy -f

Create a simple theme with a base of main theme

app/design/frontend/Leela/MyTheme/theme.xml

<theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
    <title>Leela Theme</title>
    <parent>Magento/luma</parent>
</theme>

app/design/frontend/Leela/MyTheme/registration.php

<?php
use \Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(
    ComponentRegistrar::THEME,
    'frontend/Leela/MyTheme',
    __DIR__
);

You can skip this step, and run Step 4 if you just want to register and see it in admin tool, If you want to make design changes to your theme you can create this folder structure and overwrite CSS by writing your own CSS in _extend.less. I have added some basic overwrite CSS

app/design/frontend/Leela/MyTheme/web/css/source/_extend.less

#search{

    border:red 1px solid;
}

#search_mini_form{

    .advanced {
        color:red;
    }

    .label{
        color:red;
    }

} 
Php bin/magento setup:upgrade
  1. Login to your adminstration tool of magento
  2. Go to Content -> Configuration
  3. You should see either single store or multiple store, click on Edit of the store you want to apply your theme
  4. You should see your theme name under drop down, in our case it ‘Leela Theme’ select it and click on apply
  5. Run following commands
php bin/magento setup:static-content:deploy -f
php bin/magento cache:clean

Create a new module to create link in footer links Magento 2

Leela
  └── FooterLink
      ├── registration.php
      └── etc
          ├── module.xml
      └── view          
          └── frontend
              └── layout
                     └── default.xml

app/code/Leela/FooterLink.

app/code/Leela/FooterLink/registration.php

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

app/code/Leela/FooterLink/registration.php

<?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="Leela_FooterLink" setup_version="1.0.0"/>
</config>

app/code/Leela/FooterLink/view/frontend/layout/default.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="footer_links">
            <block class="Magento\Framework\View\Element\Html\Link\Current" name="leela.footerlink" before="-">
                <arguments>
                    <argument name="label" xsi:type="string">Custom Link</argument>
                    <argument name="path" xsi:type="string">/footerlink</argument>
                </arguments>
            </block>
        </referenceBlock>
    </body>
</page>

php bin/magento setup:upgrade
php bin/magento cache:clean

This will add a new link to the footer links section in Magento 2. You can modify the label and path attributes to customize the link.

How to create a new module in Magento 2

app/
└── code/
    └── Leela/
        └── RemoveNewsLetter/
            ├── registration.php
            └── etc/
                └── module.xml
            └── view/
                └── frontend/
                    └── layout/
                        └── default.xml

in the app/code directory of your Magento installation.

The directory structure should be: app/code/Leela/RemoveNewsLetter/.

Create “app/code/Leela/RemoveNewsLetter/registration.php

with the following content:

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

app/code/Leela/RemoveNewsLetter/etc/module.xml

with the following content:

<?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="Leela_RemoveNewsLetter" setup_version="1.0.0" />
</config>

app/code/Leela/RemoveNewsLetter/view/frontend/layout/default.xml

with the following content:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="form.subscribe" remove="true" />
    </body>
</page>

Run the following command in your root directory

php bin/magento setup:upgrade

That’s it! The above module will remove the newsletter section from your Magento store’s frontend.

Configuring Xamp sendmail localhost

You should enable following module in php.ini file.

Step 1 - Create App password from your google account settings
  • Go to your Google Account.
  • Select Security.
  • Under “Signing in to Google,” select App Passwords. You may need to sign in.
  • If you don’t find it under security you need to click on 2 factor security and complete the security process and then
  • At the bottom inside 2 factor security option choose Select app and choose the app you using Select device and choose the device you’re using. …
  • Follow the instructions to enter the App Password. …
  • Tap Done.
Step 2 - Configuring your PHP.ini configuration
Enable below module by removing semicolon in front of it
C:\xampp\php\php.ini find extension=php_openssl.dll

Update following values in php.ini

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = <Your gmail id>
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"

Update following values in C:\Xamp\sendmail\sendmail.ini

smtp_server=smtp.gmail.com
smtp_port=587
smtp_ssl=TLS
sendmail_from = <Your gmail id>
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
auth_username=<Your gmail id>
auth_password=<generated password from googgle app password>

Stop and start the apache from Xampp control panel

Installing Magento 2 in windows operating system using XAMPP and composer

Before we start the installation process of Magento 2, first we need to understand what are the prerequisites that we need to have in our system. The following URL will show you system requirements table along with the combination versions of softwares you need to install the Magento 2

https://experienceleague.adobe.com/docs/commerce-operations/installation-guide/system-requirements.html

After thorough research, one of the combinations of versions that I am going to use in this article. To install and run Magento application we need following applications in our system (in this scenario it is windows operating system)

  • Server – (here I am going to choose Apache),
  • PHP
  • Database – (here I am going to choose MySQL, you can choose any database but you need to configure your Magento accordingly).
  • Search Engine – (here I choose elastic search, you can choose any search engine, again you need to configure your Magento accordingly)
  • Composer – Package management

Here I can choose to either install Server, PHP and Mysql Separately or I can install XAMP which actually provides all these three as a package.

You can download the XAMPP from the following link

  • Open a link www.apachefriends.org
  • Click on the Downloads button from the top menu
    • https://www.apachefriends.org/download.html
    • You will see three sections one for each operating system, under windows operating system by default you should be seeing the latest version of XAMPP, as of today it is (8.0.25, 8.1.12 & 8.2.0) Click on the “More Downloads” link under windows OS section to look out for different version.
    • https://sourceforge.net/projects/xampp/files/
    • Now you should see a folder called “XAMPP Windows” folder, click on that and then click on  7.4.30.
    • Install the XAMPP just like any other windows software, just remember where you are storing your XAMPP folder for future reference.
  • The reason that I have taken the 7.4.30 file is for compatibility issues, you can try and explore different versions combinations, here in this XAMP version you will get PHP 7.4.30
2.1 Our next step is making PHP globally available, which means if you run php -v command in the PowerShell/command prompt you should see php version.

To achieve this we need to add a PHP path to environmental variable windows. First, you need to identify the PHP path,

If you have installed your XAMPP in C\XAMPP drive the PHP path would be C:\XAMPP\php, in some cases, you should see the bin folder PHP. End of the day whether you installed your PHP using XMAPP or separately you should always point your path to PHP executable file.

  • Now you add that PHP path to the Windows Environment Variable Path
    • On the Windows taskbar, right-click the Windows icon and select System.
    • In the Settings window, under Related Settings, click Advanced system settings.
    • On the Advanced tab, click Environment Variables.
    • Click New to create a new environment variable. Click Edit to modify an existing environment variable.
    • After creating or modifying the environment variable, click Apply and then OK to have the change take effect.

After you successfully add the PHP path, close and open the PowerShell if it is opened and then try the command php -v, in any path of the windows you should be able to see the PHP version.

2.2 Our next step is to install and enable all the necessary extensions of php to support the Magento2 installation and running.

Following are the extensions you need to enable

gd2, intl, soap, xsl, sockets, sodium
  • These extensions can be enabled under php.ini file, you can get to this file in two ways
    • Under XAMPP control panel next to Apache, you will find the config button, click on that you see php.ini click on that it will open php.ini file
    • You can open the file from C:\XAMPP\php\php.ini
    • Once you open the file, and search for gd or gd2 you will see the extension is commented using a semicolon (;extension=gd2), remove that semicolon (extension=gd2) which will enable the extension, and you need to do the same process for all extensions mentioned above.
    • Copy php/libsodium.dll to apache/bin/
    • Restart the apache server by clicking stop and start on XAMP control panel.

You also need to increase the memory limit under the same php.ini file

  • max_execution_time=18000
  • max_input_time=1800
  • memory_limit=4204M

Since we made PHP global, now we can install composer in our system using php commands, you can install composer using an exe file. I am going to install composer using the command line. First I will create a folder under C:\ComposerFile, get into this folder in your PowerShell or command prompt and then run the below commands

Step 3.1 Installing Composer using command line with php prerequisites

You need to run the following three commands, I will also explain what each command means. The source of these commands is from https://getcomposer.org/download/

First Command 
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

###############
##To download composer-setup.php.
###############


Second Command
php -r "if (hash_file('sha384', 'composer-setup.php') === '55ce33d7678c5a611085589f1f3ddf8b3c52d662cd01d4ba75c0ee0459970c2200a51f492d557530c71c15d8dba01eae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

###############
##To simply verify the downloaded composer-##setup.php wether the file is really downloaded from the ##getcomposer.org or not
###############


Third Command
php composer-setup.php

###############
## the above command will create composer.phar  when we compile it using php command. You can keep this file some where safe for future reference
###############

####Now you can run command 
composer.phar -V
##this command will show you the version of the composer. 

Now your composer is successfully installed in your system but it is just that every time you need to use composer.phar if you want to run any composer command, sometimes if you are in a different folder from where composer.phar file exists you need to give the full path of the composer.phar file to run the composer command which will be annoying so we need to make composer global just like we did with php

Step 3.2 - Making sure our composer.phar is globally available and instead of calling composer.phar every time we can we can call only composer to run any composer commands.

To achieve this first we need to convert our composer.phar to composer.bat, you need to make sure where ever you are running any one of the following command your composer.phar file should exist we are creating composer.bat file from composer.phar. In our case we are running underC:\ComposerFile. The source of following commands are https://getcomposer.org/doc/00-intro.md#installation-windows

###Using cmd.exe: If you are using command prompt
C:\ComposerFile> echo @php "%~dp0composer.phar" %*>composer.bat

###Using PowerShell: If you are using PowerShell
C:\ComposerFile> Set-Content composer.bat '@php "%~dp0composer.phar" %*'

After running the command you should be able to see composer.bat file under C:\ComposerFile folder, now you need to add this path(C:\ComposerFile) to Environment Variables. Please follow same process that is mentioned under PHP above environment variables.

Now you should be able to run the composer command from any path in your PowerShell or Command prompt.

And one final command we need to run, this is to downgrade our composer to 1, the reason we are downgrading is there is an issue with PHP8 and libsodium library, and composer2 runs on PHP8 but our PHP version is PHP7, composer 1 runs in PHP 7, so I am using composer 1 for my Magento installation process. You can use different software combination versions.

Following is the command you can use, this command will install last latest version of composer1

composer self-update --1
Step 4.1 - Installing elastic search engine

I choose the elastic search 7 version, you can download it from the following link
https://www.elastic.co/downloads/past-releases/elasticsearch-7-17-9

Since we are working on the Windows operating system, please download the Windows file, after you download it, you can extract the zip file, rename the folder to elasticsearch7 and keep this folder under C:\elasticsearch7.

  • Now you can do either 4.2 or 4.3, you can get information about both ways in the following links
    • 4.2 – https://www.elastic.co/guide/en/elasticsearch/reference/current/zip-windows.html#windows-running
    • 4.3 – https://www.elastic.co/guide/en/elasticsearch/reference/current/zip-windows.html#windows-service
Step 4.2 - Running elastic search directly

In this way, you can simply run the elasticsearch.bat file from the bin folder from either PowerShell or Command prompt. Get into folder C:\elasticsearch7 and run the following command

.\bin\elasticsearch.bat

### here you need to keep open the Powershell, you can minimize it but not close it since elastic search is running, but if you use step 4.3 this is not required
Step 4.3 - Running elastic search as a service
  1. Install Elasticsearch as a service. The name of the service and the value of ES_JAVA_HOME will be made available during install:
    • C:\elasticsearch7\bin>elasticsearch-service.bat install
  2. Start Elasticsearch as a service. When Elasticsearch starts, authentication is enabled by default:
    • C:\elasticsearch7>.\bin\elasticsearch-service.bat start

After successful running of elastic search using either 4.2 or 4.3 you should be able to see a JSON object with a elastic search engine information when you run localhost:9200(Please make sure that the 9200 port is available before you start the elastic search, usually it will be available)

You need to start elastic search whenever it stopped using the very same command. You have stop, remove, and manager commands available in the very same link provided above for both 4.2 and 4.3 in bullet points, feel free to explore.

Step 5.1 - Please create adobe id and login into marketplace.magento.com with that adobe id.

This is where you need to create adobe id and login into marketplace.magento.com using adobe id. Once you login you need to top right side where you see your name click on that, dropdown with two menu options will appear (signout, myprofile), click on “My Profile”.

Now you see under “My Products-> Access Keys”. Create a New access key with any name by clicking on the button “Create New Access Key”.

Once after giving a name to access key and click on save you should see public key and private key these are your username and password which will be asked when you install magento2 using composer command in Step 5.2

Step 5.2 - Downloading Magento 2.4.5 using composer command

You can get information about composer create command for Magento 2 to download Magento community or commerce version in the following link

https://experienceleague.adobe.com/docs/commerce-operations/installation-guide/composer.html?lang=en

Following is the command that will be used to download the Magento 2 community edition. I will create a folder called “MagentoProjects” in the desktop of the windows and I will enter into it using either PowerShell or Command Prompt and run the following command

composer create-project --repository-url=https://repo.magento.com/  magento/project-community-edition:2.4.5 magentoone

In the above command “Magentoone” is the folder name which I have given as a project name and this is where all the Magento files will be downloaded. When the download starts it will ask for the user and password. Please enter the username(public Key) and password(Private Key) which you created in Step 5.1

Step 6.1 Enabling the following modules if they are not in C:\XAMPP\apache\conf\httpd.conf

Once you open this file you should be seeing following modules in httpd.conf

Find below lines and change them from 

#LoadModule version_module modules/mod_version.so
#LoadModule vhost_alias_module modules/mod_vhost_alias.so
#LoadModule rewrite_module modules/mod_rewrite.so
#Include conf/extra/httpd-vhosts.conf

To (Removing # means you are uncommenting them so they will be enable)
LoadModule version_module modules/mod_version.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
Include conf/extra/httpd-vhosts.conf
Step 6.2 - Configuring your virtual host in your apache vhosts file

Once you done with these changes you need to open another file from C:\XAMPP\apache\conf\extra\httpd-vhosts.conf and add following code to it. This is a virtual host setup where you can create a host for your Magento application, it may change depending on your server. We are actually creating localhost domain names with localhost and port. For our example we have taken 8081, creating virtual host with 8081 port is not enough you need to make sure you tell apache to expose that port number using. Listen 8081

You also see here that Directory tag added inside virtual host, this is very crucial for your website to run, you are allowing apache server to access the root folder using this tag

 
Listen 8081
<VirtualHost *:8081>
    ServerAdmin engage@vlpreddy.com
    DocumentRoot "C:\Users\user\MagentoProjects\Magento\magentoone\pub"
    ##ServerName dummy-host2.example.com
    ErrorLog "C:\Users\user\Desktop\MagentoProjects\magentoone\error.log"
    CustomLog "C:\Users\user\Desktop\MagentoProjects\magentoone\access.log" common
    <Directory C:\Users\user\Desktop\MagentoProjects\magentoone> 
        AllowOverride All
        Options Indexes FollowSymLinks
        Require all granted
    </Directory>
</VirtualHost>


######
C:\Users\user\Desktop\Magento\magentoone\pub. -> this is the root folder of the magento application, it's been like this since 2.4, before 2.4 the root folder was directly "magentoone" folder.

Note : Make sure what ever the path your are using under virtual host is same as the path where you have downloaded the magento using composer command in the above Step 5
######

and stop and start the apache using XAMPP control panel

Step 7.1 - Creating database, user and assign user to database

Goto localhost/phpmyadmin ,

  • Create database by clicking on Database menu
  • Create a user –
    • First click on a created database which listed in the left side
    • check for the “privileges” link on the top menu next to “operations” link, if it is not visible click on the “more” link you should see the “privileges” link under the menu
    • At the bottom you see the “Add user account” link, with this you can create new user, make sure you select a check box saying “grant all privileges on database <what ever you have selected at the first bullet point in the list>”. This check box will only appear when you click on “privileges” after you click on the selected database in this case its “magentoone”
Step 7.2(optional) - Configuring mysql if re-indexing runs slow while running Magento commands 

You need to update following options under C:\XAMPP\mysql\bin\my.ini

long_query_time = 1
innodb_buffer_pool_size = 5024
innodb_thread_concurrency = 4
innodb_flush_log_at_trx_commit = 2
thread_cache_size = 32
query_cache_size = 64M 
query_cache_limit = 2M 
join_buffer_size = 8M
tmp_table_size = 256M
key_buffer = 32M
innodb_autoextend_increment = 512

To avoid slow reindex(my.ini)
optimizer_switch='rowid_filter=off'
optimizer_use_condition_selectivity = 1
Step 8.1 - Before you run php Magento install command you need to fix few things 

We need to run php install command but we need update the code in the following files, since we already know these issues will come while installing Magento so we fix these files first and then run php command. Please follow instructions for the following three. I am also defining what errors we might get if we don’t fix these changes. All the paths you see below are from Magento root folder “Magentoone”

Error 1 - Gd2.php file error

Solution: 
Find "validateURLScheme" function in vendor\magento\framework\Image\Adapter\Gd2.php file. at line 92. Replace function with this: 

private function validateURLScheme(string $filename) : bool
{
          $allowed_schemes = ['ftp', 'ftps', 'http', 'https'];
          $url = parse_url($filename);
          if ($url && isset($url['scheme']) && !in_array($url['scheme'], $allowed_schemes) && !file_exists($filename)) {
              return false;
          }

          return true;   
}
Error 2 -  You website css and javascript won't work properly

Solution :
Go to: vendor\magento\framework\View\Element\Template\File
Edit Validator.php using a text editor and find this line:
instead of the line
strpos($realPath, $directory)
use
strpos($path, $directory)


Error 3 -  You website css and javascript won't work properly

Solution:
Open up app/etc/di.xml in the editor,
– Find the path “Magento\Framework\App\View\Asset\MaterializationStrategy\Symlink” and replace to “Magento\Framework\App\View\Asset\MaterializationStrategy\Copy”

Once you done with all changes you can open the PowerShell or Command Prompt go to the Magento root folder which is C:\Users\users\Desktop\MagentoProjects\Magentoone and run the following command

Step 8.2 - Installing Magento using PHP Magento Install command
php bin/magento setup:install --base-url=http://localhost:8081 --db-host=localhost --db-name=magentoone --db-user=leela1 --db-password=Red123# --admin-firstname=admin --admin-lastname=admin --admin-email=admin@admin.com --admin-user=admin --admin-password=admin123 --language=en_US --currency=USD --timezone=America/Chicago --use-rewrites=1 --search-engine=elasticsearch7 --elasticsearch-host=localhost --elasticsearch-port=9200  --elasticsearch-timeout=15

Once after successfully completion of the above command you need to run the following commands one by one, some commands may take a while, so not to worry wait until all these commands complete.


php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy -f
php bin/magento indexer:reindex
php bin/magento cache:flush
Error 4 : When you run php bin/magento setup:di:compile
 command if you get this error (Plugin Generator error)

Solution:
Open PluginListGenerator.php file located at vendor/magento/framework/Interception.
Go to line no 158 or find the word “scopePriorityScheme” in PluginListGenerator.php file.
Replace the line
"$cacheId = implode('|', $this->scopePriorityScheme) . "|" . $this->cacheId;" with"$cacheId = implode('-', $this->scopePriorityScheme) . "-" . $this->cacheId;"

and run the compile command again, after that complete remaining commands static-content, reindex, flush

That’s it that’s the end of the Magento Installation process in windows.

  • Now you can access
    • your store website under localhost:8081
    • You admin under localhost:8081/admin (after 2.4.3 i guess it will show admin url after success install).
    • You can also get admin url by running following command
      • php bin/magento info:adminuri

When you try to access your admin using the credentials your enter while running install command your admin fails to login, to resolve this issue you need to disable the twofactor authentication by running following command

  • php bin/magento module:disable Magento_TwoFactorAuth
  • php bin/magento cache:flush

Installing Drupal Drush in windows and linux

To install Drush on your system, you can follow these steps:

  1. Check if you have PHP installed on your system by running the command php -v in your terminal. If PHP is not installed, you’ll need to install it first.
  2. Install Composer, which is a dependency manager for PHP. You can download and install Composer by following the instructions on the official Composer website: https://getcomposer.org/download/
  3. Once Composer is installed, you can use it to install Drush by running the following command in your terminal.
composer global require drush/drush 

  1. This command will download and install Drush globally on your system, so you can use it from any directory in your terminal.
  2. Finally, add the Drush executable to your system’s PATH environment variable so you can use the drush command from any directory in your terminal. You can do this by adding the following line to your shell configuration file (such as ~/.bashrc or ~/.zshrc):
export PATH="$HOME/.composer/vendor/bin:$PATH" 

##we use this if we install composer using installation file

OR

export PATH="$HOME/.config/composer/vendor/bin:$PATH" 

#we use this if we install composer using commands and moved composer.phar manually to bin
  1. Save the file, and then reload the shell configuration by running source ~/.bashrc or source ~/.zshrc in your terminal.

After completing these steps, you should be able to use the drush command to manage your Drupal site from the command line.

How can i add drush executable globally in windows?

To add the Drush executable globally on Windows, you can follow these steps:

  1. Open a command prompt with administrator privileges. To do this, right-click on the Command Prompt icon and select “Run as administrator”.
  2. Type the following command to check if Composer is installed on your system
composer --version 

  1. If Composer is not installed, you can download and install it from the official Composer website: https://getcomposer.org/download/
  2. Use Composer to install Drush globally by running the following command
composer global require drush/drush
  1. Once the installation is complete, you need to add the Drush executable to your system’s PATH environment variable so that you can use the drush command from any directory in your command prompt. To do this, follow these steps:
    • Click on the Start button and search for “Environment Variables”.
    • Select “Edit the system environment variables”.
    • Click on the “Environment Variables” button.
    • In the “System variables” section, scroll down and find the “Path” variable, then click on the “Edit” button.
    • Click on the “New” button and add the path to the Drush executable. The path is usually %USERPROFILE%\AppData\Roaming\Composer\vendor\bin. Click on “OK” to close all windows.
  2. Close and reopen your command prompt, then type the drush command to verify that it’s working. You should see the Drush version information printed in the console.

That’s it! You have now installed Drush globally on your Windows system and added it to your system’s PATH environment variable.