How to Set Up and Manage a Magento 2 Git Workflow?
Facing problems with your store’s code due to disorganized development practices? Magento 2 Git workflows prevent lost work and project errors. Chaotic code management blocks team collaboration and delays project launches.
This tutorial shows how to set up Git essentials.
Key Takeaways
-
Git helps developer teams manage Magento 2 code.
-
Using .gitignore helps keep your project repository clean.
-
Setting up new Magento projects with Git steps helps develop new features.
-
Composer manages project dependencies for consistency and updates.
-
A good branching strategy keeps your project code stable.
-
Example Simple Git Workflow for Magento 2 Feature Development
-
Managing Composer Dependencies and the vendor Directory with Git
What is Magento 2 Git?
“Magento 2 Git is a method to track collaborative project development. Git is a distributed version control system for code.”
The platform stores its code on GitHub, which serves as the main codebase for Magento Open Source.
The repository contains key components for all projects, including:
-
Modules for payments or inventory management.
-
Themes for storefront design and user experience.
-
Libraries containing different reusable code functions.
Developers access core files through this Git repository. Teams track code changes and manage versions together. Git integration lets developers customize online eCommerce stores.
The system maintains a history of code modifications. Branching permits development without affecting the production code.
Adobe maintains the official Magento 2 GitHub repository. Community members contribute through pull requests and issues.
.gitignore
File
The Essentials of Magento 2 .gitignore
Pattern Format
1. The .gitignore file defines untracked file patterns. Git excludes specified files from version control tracking. Developers prevent unnecessary files from entering the repository.
Pattern matching follows rules and conventions. Lines starting with #
represent comment entries. Blank lines serve as separators for readability.
The forward slash /
indicates directory separation. Asterisks **
match against full pathname structures. Exclamation marks !
negate previous exclusion patterns.
2. Core Files to Exclude
Magento generates temporary files during operation. The var/
directory contains cache and log files. Session data accumulates in the var/session/
folder.
Generated code resides in the generated/
directory structure. Static content deployment creates files in pub/static/
. Media uploads populate the pub/media/
directory.
Configuration files like app/etc/env.php
contain sensitive data. Database credentials need protection from repository exposure. API keys must remain outside version control systems.
3. Managing Composer Dependencies
The vendor/
directory contains third-party packages and libraries. Composer-managed, it auto-updates dependencies without cluttering the repository. Composer handles dependencies through the composer.lock
file.
Standard practice excludes the entire vendor directory. The composer.json
file defines required package versions. Teams run composer install
to restore dependencies.
Vendor exceptions include:
-
/vendor/.htaccess
- Security configuration file -
Custom vendor patches requiring version control
-
Modified vendor files that need team synchronization
4. Repository Performance
Large files impact Git performance and clone speed. Github imposes limitations related to file size and blocks files larger than 100 MB. Binary files need careful consideration before repository inclusion.
Archive files consume repository storage space. Common exclusions include:
-
*.zip
- Compressed archive files -
*.tar.gz
- Tarball archives -
*.sql
- Database dump files -
*.log
- Application log files
IDE files clutter the repository without value. Exclude .idea/
for PhpStorm project configurations. Operating system files like .DS_Store
needs exclusion.
7 Steps to Establish a New Magento 2 Git Project
Step 1: Verify System Prerequisites
Development requires software installations before starting.
-
PHP: Magento 2 requires PHP (version 8.1 or later recommended).
-
Composer manages PHP dependencies throughout the project lifecycle.
-
Docker: Sets up the environment by containerizing services.
-
Git provides version control for code management.
-
MySQL or MariaDB serves as the database backend.
System requirements for Magento 2.4.8 include:
-
PHP 8.2 or PHP 8.3
-
Composer version 2.x
-
Elasticsearch 8.x
-
Redis 7.0 or higher
-
Varnish 7.x for caching
Step 2: Create Project Directory Structure
Organize the development environment with a proper directory hierarchy. Create a dedicated workspace for Magento projects. Structure separates client projects and versions.
mkdir -p ~/projects/magento2/client-name
cd ~/projects/magento2/client-name
Directory naming follows consistent patterns across all projects. Teams locate projects quickly using standardized paths. Backup scripts target organized directory structures.
Step 3: Clone the Magento Repository
Terminal access initiates the repository cloning. Go to the desired project directory location. Execute the clone command to download Magento code.
git clone https://github.com/magento/magento2.git .
git checkout 2.4.8
The command creates a local repository copy. Git downloads the complete codebase and history. The checkout command now switches to a stable version 2.4.8.
Step 4: Configure Authentication Credentials
The Magento repo needs login info to download packages. Get your login keys from the Magento Marketplace. Save your login info in Composer.
composer config http-basic.repo.magento.com <public-key> <private-key>
The public key serves as the username. The private key functions as the password for authentication. Credentials save in the global Composer configuration file.
Step 5: Install Dependencies via Composer
Composer checks the composer.json
file for dependencies. Run: composer install
. It downloads all needed packages listed in composer.json
into the vendor folder.
composer install --no-dev
Production environments benefit from excluding development dependencies. The --no-dev
flag is for deployment installation. The lock file keeps dependency versions consistent across environments.
Step 6: Configure Git for the Project
Configure Git with developer identity information. Set the project username and email for commit attribution. Local configuration overrides global settings when necessary.
git config user.name "Developer Name"
git config user.email "developer@example.com"
git remote add origin git@github.com:company/project.git
The remote repository stores the team's collaborative work. SSH authentication provides secure repository access for developers. The "origin" naming convention identifies the primary remote repository.
Step 7: Initialize Project Repository
Create the initial commit after dependency installation. Add the custom .gitignore
file to the repository tracking. The commit message should describe the project initialization.
curl -O https://raw.githubusercontent.com/magento/magento2/2.4-develop/.gitignore
git add .gitignore composer.json composer.lock
git commit -m "Initialize Magento 2.4.8 project"
git push -u origin main
The push command uploads code to the remote repository. Upstream tracking helps with future push and pull operations. Team members clone the initialized project for development.
Example Simple Git Workflow for Magento 2 Feature Development
1. Creating Feature Branches
Feature development starts with creating dedicated branches. Branch names describe the feature or issue. Developers isolate changes from the main codebase.
git checkout -b feature/payment-gateway-integration
The command creates and switches to a new branch. Work proceeds without affecting other developers. Feature branches merge back after completion and testing.
Branch naming conventions help team collaboration. Common patterns include:
-
feature/description
- New feature development -
bugfix/issue-number
- Bug fix branches -
hotfix/critical-issue
- Emergency production fixes -
release/version-number
- Release preparation branches
2. Making Code Changes
Module development follows Magento's structural conventions. Create modules in the app/code/Vendor/ModuleName
directory structure. Each module contains directories for functionality organization.
Module directories include:
-
etc/
- Configuration files -
Model/
- Business logic classes -
Controller/
- Request handling logic -
view/
- Frontend templates and layouts
Stage changes happen during development. Use 'git add -p'
to select changes. Write commit messages to explain each change.
3. Committing and Pushing Changes
Atomic commits help code review and history clarity. Each commit addresses a single concern or feature. Messages follow a conventional format for consistency across teams.
git add app/code/Vendor/ModuleName/
git commit -m "Add payment gateway integration module"
git push origin feature/payment-gateway-integration
Push commits to prevent local data loss. Remote branches allow collaboration with team members. Force pushing disrupts other developers' work and history.
4. Creating Pull Requests
Pull requests incite code review and discussion. The GitHub interface provides tools for collaborative reviews. Team members comment on code lines.
PR descriptions should include:
-
Summary of changes
-
Testing steps for reviewers
-
Related issue numbers
-
Screenshots for UI changes
Reviewers examine code quality and adherence to standards. Automated tests check functionality before merging. Approved changes merge into the main development branch.
vendor
Directory with Git
Managing Composer Dependencies and the 1. Composer Lock File Strategy
The composer.lock
file maintains dependency version consistency. Teams should always commit this file to version control. Installation uses the exact versions specified in the lock file.
Lock file updates occur through composer commands. Run composer update
only in development environments. Production deployments use composer install
for stability.
Version constraints in composer.json
control update behavior:
-
^2.4.0
- Compatible updates within the major version -
~2.4.0
- Updates to 2.4.x only -
2.4.0
- Exact version requirement -
>=2.4.0
- Minimum version specification
2. Handling Custom Composer Packages
Private packages demand repository configuration in composer.json
. Authentication credentials stay outside version control. Teams share package access through repository permissions.
{
"repositories": [
{
"type": "vcs",
"url": "https://github.com/company/private-module"
}
]
}
Custom packages follow semantic versioning for compatibility. Tags mark stable releases for production deployment. Development branches allow testing before official releases.
3. Dependency Update
Updates maintain security and performance standards. Schedule updates during development sprints for testing time. Document breaking changes in commit messages and notes.
Update steps:
-
Create a dedicated update branch
-
Run
composer update
-
Test the affected functionality
-
Commit lock file changes
-
Move to the staging environment
-
Merge after successful checks
Major version updates need extensive compatibility testing. Extension vendors provide upgrade guides for breaking changes. Rollback plans prepare teams for potential issues.
4. Managing Module Dependencies
Modules declare dependencies through their composer.json
files. Magento checks requirements during module installation. Circular dependencies cause installation failures and conflicts.
Module dependency practices:
-
Specify minimum compatible versions
-
Avoid unnecessary dependency chains
-
Test with the latest stable versions
-
Document system requirements
Third-party modules introduce extra dependency complexity layers. Vendor support determines long-term module viability and maintenance. Audits identify outdated or vulnerable dependencies.
Magento 2 Git Branching Strategy & Practices
1. Main Branch Protection
Production code resides in the main branch. The main branch holds stable production code. Direct commits to the main need restriction through settings.
Branch protection rules enforce quality and stability standards:
-
Demand pull request reviews
-
Pass status checks
-
Enforce up-to-date branches
-
Restrict force pushes
Administrator approval allows emergency hotfix deployment procedures. Documentation explains override procedures for critical situations. Branches handle all standard development work.
2. Development Branch Management
The develop branch holds all feature work. The develop branch acts as the integration hub for new features. Automated tests run against every development branch commit.
Daily integration identifies conflicts between features early. Developers pull the latest changes before starting work. Merge conflicts resolve with fresh code context.
Integration branch practices include:
-
Synchronization with the main
-
Feature freeze before releases
-
Automated deployment to staging
-
Test suite runs
3. Release Branch
Release branches prepare versions for production deployment. Version numbers follow semantic versioning conventions. Final testing occurs in dedicated release branch environments.
git checkout -b release/2.4.8
git tag -a v2.4.8 -m "Release version 2.4.8"
Release branches accept only critical bug fixes. Feature development continues in parallel on the develop branch. Merges flow back to both main and develop.
4. Hotfix Strategy
Critical production issues need immediate fixing through hotfixes. Hotfix branches originate from the main branch. Minimal changes reduce the risk of further problems from emerging.
Hotfix steps:
-
Create a branch from the main
-
Apply only a minimal fix
-
Test in a production-like environment
-
Push to production
-
Merge with the main and develop
Post-deployment monitoring confirms the issue fixtures. Root cause analysis prevents similar issues from recurring. Documentation updates reflect lessons learned from incidents.
FAQs
1. How does Magento 2.4.8 handle Git submodules for extension management?
Magento 2.4.8 favors Composer over Git submodules. Submodules can add complexity and are not ideal for this use case. Composer offers better dependency management. Extension installation happens via 'composer require vendor/module'
. It handles transitive dependencies without manual effort.
2. What measures protect sensitive data in Git repositories?
Exclude environment configuration files from repositories. app/etc/env.php
, for example, contains database credentials. Ignore other sensitive files to prevent risks. Other measures include API keys in environment variables. Encrypted credentials, access control lists, and audits are also alternatives.
3. How do teams handle database schema changes in Git?
Magento uses a declarative schema for database version control. Schema files track structural changes in etc/db_schema.xml
. The system generates patches during deployment. Setup scripts remain for complex data migrations. Version numbers in module.xml
control the run order. Rollbacks can protect against failed schema updates.
4. Which Git hooks enhance Magento 2 development?
Pre-commit hooks check code standards before commit creation. A hook can run PHP CodeSniffer for PSR-12 compliance to prevent syntax errors in commits. Useful Git hooks include: pre-commit for code quality, prepare-commit-msg for message format. Post-merge handles dependency updates and pre-push for tests.
5. How does branching strategy differ for multi-store setups?
Multi-store projects need store-related feature branch names like "feature/us-store/checkout-update". This reflects configuration changes for individual views. Testing should cover all stores before completion for clarity and identification.
6. What strategies prevent merge conflicts in large teams?
Integration cuts conflict complexity. Fixing time through small commits, automated detection, and refactoring. Communication, a shared architecture, and clear ownership support conflict prevention. Feature flags and team agreements also play a role.
Summary
Magento 2 Git offers version control for team projects. It tracks all code changes in a shared repository. Consider the points mentioned below for setting up any simple Git project workflow:
-
Clone the official Magento repository from the source. Install all project dependencies using the Composer tool.
-
Use the
.gitignore
file to exclude specific folders. This keeps the repository clean from temporary files. -
Create feature branches for all new development work. Merge your changes back using a pull request.
-
Protect the main branch from any direct commits. Use hotfix branches for any urgent production fixes.
-
Commit the
composer.lock
file to your repository. Keep the large vendor directory out of tracking.
Consider Managed Magento Hosting for expert support with Git workflow maintenance.