2 min read

Fish Shell Function to Run PHP Composer in Docker

It’s really nice to always has clean machine, that’s why I always try to use Docker to isolate certain commands.

Instead of installing PHP Composer globally, I prefer to create a helper function for my Fish Shell that, under the hood, runs a docker image.

~/.config/fish/functions/composer.fish
function composer
    set -l composer_version "latest"  # Default version
 
    # Check if the first argument is a version number (e.g., "2" or "2.8.4")
    if string match -qr '^[0-9]+(\.[0-9]+)*$' -- $argv[1]
        set composer_version $argv[1]  # Assign version
        set argv $argv[2..-1]  # Shift arguments (remove first argument)
    end
 
    # Set Composer environment variables for home and cache directories
    set -q COMPOSER_HOME; or set -x COMPOSER_HOME "$HOME/.config/composer"
    set -q COMPOSER_CACHE_DIR; or set -x COMPOSER_CACHE_DIR "$HOME/.cache/composer"
 
    # Define colors
    set color_composer "\e[32m"    # Green
    set color_version "\e[37m"     # White
    set color_number "\e[93m"      # Bright Yellow/Gold
    set color_reset "\e[0m"        # Reset color
 
    # Display formatted version message
    echo -e "$color_composer""Composer""$color_reset $color_version""version""$color_reset $color_number$composer_version$color_reset"
 
    # Run Composer in Docker with home & cache directories
    docker run --rm --interactive --tty \
        --env COMPOSER_HOME="$COMPOSER_HOME" \
        --env COMPOSER_CACHE_DIR="$COMPOSER_CACHE_DIR" \
        --volume "$COMPOSER_HOME:$COMPOSER_HOME" \
        --volume "$COMPOSER_CACHE_DIR:$COMPOSER_CACHE_DIR" \
        --volume (pwd):/app \
        --user (id -u):(id -g) \
        composer:$composer_version $argv
end

Now, we can call composer as usual without polluting our machine. To use a specific tag, just pass it after composer, like this: composer 2.8 -v.