How to install composer linux

Introduction#

Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.

Dependency management#

Composer is not a package manager in the same sense as Yum or Apt are. Yes, it deals with «packages» or libraries, but it manages them on a per-project basis, installing them in a directory (e.g. vendor ) inside your project. By default, it does not install anything globally. Thus, it is a dependency manager. It does however support a «global» project for convenience via the global command.

This idea is not new and Composer is strongly inspired by node’s npm and ruby’s bundler.

  1. You have a project that depends on a number of libraries.
  2. Some of those libraries depend on other libraries.
  1. Enables you to declare the libraries you depend on.
  2. Finds out which versions of which packages can and need to be installed, and installs them (meaning it downloads them into your project).
  3. You can update all your dependencies in one command.

See the Basic usage chapter for more details on declaring dependencies.

System Requirements#

Composer requires PHP 5.3.2+ to run. A few sensitive php settings and compile flags are also required, but when using the installer you will be warned about any incompatibilities.

To install packages from sources instead of plain zip archives, you will need git, svn, fossil or hg depending on how the package is version-controlled.

Composer is multi-platform and we strive to make it run equally well on Windows, Linux and macOS.

Installation — Linux / Unix / macOS#

Downloading the Composer Executable#

Composer offers a convenient installer that you can execute directly from the command line. Feel free to download this file or review it on GitHub if you wish to know more about the inner workings of the installer. The source is plain PHP.

There are in short, two ways to install Composer. Locally as part of your project, or globally as a system wide executable.

Locally#

To install Composer locally, run the installer in your project directory. See the Download page for instructions.

The installer will check a few PHP settings and then download composer.phar to your working directory. This file is the Composer binary. It is a PHAR (PHP archive), which is an archive format for PHP which can be run on the command line, amongst other things.

Now run php composer.phar in order to run Composer.

You can install Composer to a specific directory by using the —install-dir option and additionally (re)name it as well using the —filename option. When running the installer when following the Download page instructions add the following parameters:

Now run php bin/composer in order to run Composer.

Globally#

You can place the Composer PHAR anywhere you wish. If you put it in a directory that is part of your PATH , you can access it globally. On Unix systems you can even make it executable and invoke it without directly using the php interpreter.

After running the installer following the Download page instructions you can run this to move composer.phar to a directory that is in your path:

If you like to install it only for your user and avoid requiring root permissions, you can use

/.local/bin instead which is available by default on some Linux distributions.

Note: If the above fails due to permissions, you may need to run it again with sudo.

Note: On some versions of macOS the /usr directory does not exist by default. If you receive the error «/usr/local/bin/composer: No such file or directory» then you must create the directory manually before proceeding: mkdir -p /usr/local/bin .

Читайте также:  Руководство администратора линукс немет

Note: For information on changing your PATH, please read the Wikipedia article and/or use your search engine of choice.

Now run composer in order to run Composer instead of php composer.phar .

Installation — Windows#

Using the Installer#

This is the easiest way to get Composer set up on your machine.

Download and run Composer-Setup.exe. It will install the latest Composer version and set up your PATH so that you can call composer from any directory in your command line.

Note: Close your current terminal. Test usage with a new terminal: This is important since the PATH only gets loaded when the terminal starts.

Manual Installation#

Change to a directory on your PATH and run the installer following the Download page instructions to download composer.phar .

Create a new composer.bat file alongside composer.phar :

Add the directory to your PATH environment variable if it isn’t already. For information on changing your PATH variable, please see this article and/or use your search engine of choice.

Close your current terminal. Test usage with a new terminal:

Using Composer#

Now that you’ve installed Composer, you are ready to use it! Head on over to the next chapter for a short demonstration.

Found a typo? Something is wrong in this documentation? Fork and edit it!

Composer and all content on this site are released under the MIT license.

Источник

How to Install and Use Composer – The Complete Tutorial

In this article, we are going to show you how to install and use Composer on various platforms. Composer is a dependency manager for PHP. It is a simple and reliable tool that developers use to manage and integrate external packages or libraries into their PHP-based projects. This way, they don’t have to build their webpages or web applications from the ground-up.

To help you master this tool, you will also learn how to create a basic PHP project.

Before you learn how to install Composer, make sure that you have access to the command line interface on your system or server.

Installing Composer

This section will show you how to install Composer on shared hosting and operating systems like Linux, macOS, and Windows.

1. Installing Composer on Shared Hosting, Linux, or macOS

The commands to install Composer on shared hosting, Linux (PC or server), and macOS are the same.

Note that Composer comes pre-installed on Hostinger’s Premium and Business shared hosting plans. If you are using one of them, skip this part. However, if you find out that it’s outdated, you will need to update it by installing the correct version locally.

Follow this instruction to know how to install Composer on your system:

  1. Connect to your hosting account using SSH connection. You can learn how to do so from this SSH tutorial.
  2. Download Composer from the official website using the following command:
  3. Verify the installer’s signature (SHA-384) to ensure that the installer file is not corrupt. Enter:

The long string of characters in the above command (‘e0012edf…’) is the installer’s signature. It changes every time a new version of Composer comes out. Therefore, be sure to fetch the latest SHA-384 from this page.

  • Once it’s done, you may install Composer locally or globally. Local installation means that the dependency manager will be stored in your current directory, and you have to specify the path before executing corresponding commands. Meanwhile, global installation allows you to run Composer from anywhere on your system by storing it in /usr/local/bin directory. Here is how to complete both methods:
    • Local installation:
    • Global installation:

    You will get this result:

  • Once it’s done, remove the installer:
  • Test the Composer installation:

    The command line will return with this result:

    2. Installing Composer on Windows

    Getting started with Composer on a Windows machine is a bit different. No command-line instructions are necessary for downloading and installing the software.

    Simply follow these steps:

    1. Install PHP on your computer. We recommend using XAMPP for this purpose, as the process is straightforward and you can complete it in a few minutes.
    2. Once XAMPP is installed, download the latest version of Composer.
    3. Run Composer installation wizard. When it asks you to activate the developer mode, ignore it and continue with the installation process.
    4. Another window will pop up and ask you to locate the PHP command line. By default, it is in C:/xampp/php/php.exe. After specifying the location, click Next.
    5. You will be prompted with Proxy Settings. Leave the box unchecked and skip this part by hitting Next. Then, on the last window, click Install.
    6. After completing the installation, open the command prompt. Press CTRL +R, type in “cmd,” and click OK.
    7. Enter the following command:

    Great job! You now have Composer installed on your Windows computer. The installer will automatically add Composer to your PATH variable. Now you can open the command prompt and run the software from anywhere.

    Generating and Understanding composer.json

    Now comes the interesting part — using Composer in your PHP project.

    To achieve this, you need to generate a composer.json file. You can think of it as a way to lookup data from a list for Composer. This file contains packages (dependencies) that should be downloaded.

    Furthermore, composer.json also checks for version compatibility with your project. This means if you are using an older package, composer.json will let you know in order to avoid future issues.

    You have the option to create and update composer.json yourself. However, considering that this is a tutorial on automating redundant tasks, we don’t recommend you to create the file manually.

    Let’s demonstrate the usefulness of composer.json by creating a sample project.

    Our project is a simple PHP timer, which allows developers to find out how much time code takes to execute. This is highly useful for debugging and optimization purposes.

    You can follow these steps:

    1. Create a new directory for the project. Since our project is a timer, we’ll simply name the folder phptimer. To do this, execute the following command:
    2. Enter the newly created directory:
    3. Find a package or library for the project. The best place to achieve that is Packagist, where you’ll find tons of libraries to help your project development. For this tutorial, we need a timer package. To get it, simply type timer in the search bar:
      As you can see, several timer packages are available and each has a name and a small description of what it does. In this example, we choose phpunit/php-timer as it has the most downloads and most GitHub stars.
    4. Specify the desired package so Composer can add it to your project:

    The output will show the version of phpunit/php-timer:

    The caret (^) symbol is defined as the option for maximum interoperability. This means Composer will always update the package until a certain version breaks the package in some way.

    In our case, the package update range is >=1.0.9 The author

    Domantas leads the content and SEO teams forward with fresh ideas and out of the box approaches. Armed with extensive SEO and marketing knowledge, he aims to spread the word of Hostinger to every corner of the world. During his free time, Domantas likes to hone his web development skills and travel to exotic places.

    Источник

    Установка Composer Ubuntu 18.04

    Composer — это свободный пакетный менеджер для установки зависимостей и самих модулей PHP. Он разработан Нильсом Адерманом и Хорди Боггиано. С помощью скрипта можно в несколько нажатий установить нужный модуль, а также все его зависимости, например, ZendFramework или Symphony. Он широко используется разработчиками PHP скриптов.

    В этой статье мы рассмотрим как установить Composer Ubuntu 18.04 и более поздних версиях, а также как пользоваться утилитой.

    Установка Composer в Ubuntu

    Вы не можете установить программу из официальных репозиториев. Нужно скачать скрипт из официального сайта и поместить его в папку с вашим проектом. Но сначала обновите систему и установите зависимости:

    sudo apt update

    sudo apt install curl php-cli php-mbstring git unzip

    Установка Composer ubuntu может быть выполнена двумя способами. Либо локально в папку проекта, либо же глобально, для всей системы. Сначала рассмотрим как установить программу локально. Перейдите в папку проекта:

    Выполните такую команду для загрузки установочного скрипта:

    curl -sS https://getcomposer.org/installer -o composer-setup.php

    Затем запустите этот скрипт, чтобы создать файл composet.phar, который и будет использоваться для установки пакетов:

    Теперь вы можете проверить работает ли Composer:

    Теперь рассмотрим как установить программу глобально для всей системы. Вы можете скачивать файл установщика в любую папку, например, домашнюю:

    curl -sS https://getcomposer.org/installer -o composer-setup.php

    Только команда установки будет отличаться, в ней мы указываем папку, куда нужно установить скрипт:

    sudo php composer-setup.php —install-dir=/usr/local/bin —filename=composer

    Для проверки работы, вы можете выполнить команду:

    Использование Composer

    Для того чтобы указать какие пакеты нужно устанавливать используется конфигурационный файл composer.json. В нем сообщаются зависимости вашего проекта, а также их версии. Создайте этот файл в корневой папке вашего проекта. Синтаксис записей очень прост, и если вы раньше имели дело с JSON, то без проблем разберетесь:

    <
    «require»: <
    «производитель/пакет»: «версия»
    >
    «require-dev»: <
    «производитель/пакет»: «версия»
    >
    >

    Секция require отвечает за пакеты, необходимые для работы программы, а require-dev — только за пакеты для разработки. Например, для нашего проекта необходимо установить библиотеку работы с RSS Atom — picofeed. Для этого сначала откройте сайт https://packagist.org и найдите этот пакет:

    На его странице вы можете видеть команду composer, которой его можно установить, в ней полное имя, а чуть ниже версию:

    Наш файл будет выглядеть вот так:

    Для того чтобы установить все пакеты, описанные в файле конфигурации, используйте команду:

    php composer.phar install

    После установки пакетов composer создает файл autoload.php в папке vendor вашего проекта, с помощью него можно включить в проект все библиотеки, которые были установлены. Для этого достаточно подключить этот файл к проекту с помощью инструкции include или require:

    Например, возьмем небольшой пример чтения ленты rss с GitHub:

    use PicoFeed\Reader\Reader;
    use PicoFeed\PicoFeedException;

    $reader = new Reader;

    // Return a resource
    $resource = $reader->download(‘https://losst.ru/feed/’);

    // Return the right parser instance according to the feed format
    $parser = $reader->getParser(
    $resource->getUrl(),
    $resource->getContent(),
    $resource->getEncoding()
    );

    // Return a Feed object
    $feed = $parser->execute();

    // Print the feed properties with the magic method __toString()
    echo $feed;
    >
    catch (PicoFeedException $e) <
    // Do Something.
    >
    ?>

    Вы можете управлять зависимостями не только с помощью конфигурационного файла. Composer имеет несколько команд для легкого управления. Чтобы добавить пакет в зависимости проекта используйте команду require:

    php composer.phar require picofeed

    Пакет сразу же будет установлен. А теперь вы его можете удалить:

    php composer.phar remove picofeed

    Если версии пакетов устарели, то вы можете их обновить с помощью одной команды:

    php composer.phar update

    Выводы

    В этой небольшой статье мы рассмотрели как выполняется установка Composer Ubuntu 18.04 и 16.04, а также как использовать эту утилиту в своем проекте для разрешения зависимостей. Это очень удобно, когда вы можете один раз указать нужные пакеты и больше не заботиться об их установке и обновлении на других машинах.

    Источник

    Читайте также:  Инвертированные цвета windows 10
  • Оцените статью