One place for hosting & domains

      Composer

      How to Install and Use Composer on Ubuntu 20.04


      Introduction

      Composer is a popular dependency management tool for PHP, created mainly to facilitate installation and updates for project dependencies. It will check which other packages a specific project depends on and install them for you, using the appropriate versions according to the project requirements. Composer is also commonly used to bootstrap new projects based on popular PHP frameworks, such as Symfony and Laravel.

      In this tutorial, you’ll install and get started with Composer on an Ubuntu 20.04 system.

      Prerequisites

      In order to follow this guide, you will need access to an Ubuntu 20.04 server as a non-root sudo user, and a firewall enabled on your server. To set this up, you can follow our initial server setup guide for Ubuntu 20.04.

      Step 1 — Installing PHP and Additional Dependencies

      In addition to dependencies that should be already included within your Ubuntu 20.04 system, such as git and curl, Composer requires php-cli in order to execute PHP scripts in the command line, and unzip to extract zipped archives. We’ll install these dependencies now.

      First, update the package manager cache by running:

      Next, run the following command to install the required packages:

      • sudo apt install php-cli unzip

      You will be prompted to confirm installation by typing Y and then ENTER.

      Once the prerequisites are installed, you can proceed to installing Composer.

      Step 2 — Downloading and Installing Composer

      Composer provides an installer script written in PHP. We’ll download it, verify that it’s not corrupted, and then use it to install Composer.

      Make sure you’re in your home directory, then retrieve the installer using curl:

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

      Next, we’ll verify that the downloaded installer matches the SHA-384 hash for the latest installer found on the Composer Public Keys / Signatures page. To facilitate the verification step, you can use the following command to programmatically obtain the latest hash from the Composer page and store it in a shell variable:

      • HASH=`curl -sS https://composer.github.io/installer.sig`

      If you want to verify the obtained value, you can run:

      Output

      e0012edf3e80b6978849f5eff0d4b4e4c79ff1609dd1e613307e16318854d24ae64f26d17af3ef0bf7cfb710ca74755a

      Now execute the following PHP code, as provided in the Composer download page, to verify that the installation script is safe to run:

      • php -r "if (hash_file('SHA384', 'composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

      You’ll see the following output:

      Output

      Installer verified
      

      If the output says Installer corrupt, you’ll need to download the installation script again and double check that you’re using the correct hash. Then, repeat the verification process. When you have a verified installer, you can continue.

      To install composer globally, use the following command which will download and install Composer as a system-wide command named composer, under /usr/local/bin:

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

      You’ll see output similar to this:

      Output

      All settings correct for using Composer Downloading... Composer (version 1.10.5) successfully installed to: /usr/local/bin/composer Use it: php /usr/local/bin/composer

      To test your installation, run:

      Output

      ______ / ____/___ ____ ___ ____ ____ ________ _____ / / / __ / __ `__ / __ / __ / ___/ _ / ___/ / /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ / ____/____/_/ /_/ /_/ .___/____/____/___/_/ /_/ Composer version 1.10.5 2020-04-10 11:44:22 Usage: command [options] [arguments] Options: -h, --help Display this help message -q, --quiet Do not output any message -V, --version Display this application version --ansi Force ANSI output --no-ansi Disable ANSI output -n, --no-interaction Do not ask any interactive question --profile Display timing and memory usage information --no-plugins Whether to disable plugins. -d, --working-dir=WORKING-DIR If specified, use the given directory as working directory. --no-cache Prevent use of the cache -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug ...

      This verifies that Composer was successfully installed on your system and is available system-wide.

      Note: If you prefer to have separate Composer executables for each project you host on this server, you can install it locally, on a per-project basis. This method is also useful when your system user doesn’t have permission to install software system-wide.

      To do this, use the command php composer-setup.php. This will generate a composer.phar file in your current directory, which can be executed with php composer.phar.

      Now let’s look at using Composer to manage dependencies.

      Step 3 — Using Composer in a PHP Project

      PHP projects often depend on external libraries, and managing those dependencies and their versions can be tricky. Composer solves that problem by keeping track of project versions and dependencies, while also facilitating the process of finding, installing, and updating packages that are required by a project.

      In order to use Composer in your project, you’ll need a composer.json file. The composer.json file tells Composer which dependencies it needs to download for your project, and which versions of each package are allowed to be installed. This is extremely important to keep your project consistent and avoid installing unstable versions that could potentially cause backwards compatibility issues.

      You don’t need to create this file manually – it’s common to run into syntax errors when you do so. Composer offers an interactive way to create a new composer.json file based on the user’s input, which is a good choice if you plan on sharing your project later as a public package on Packagist. Composer also auto-generates a barebones composer.json file when you run a composer require command to include a dependency in a newly created project.

      The process of using Composer to install a package as dependency in a project involves the following steps:

      • Identify what kind of library the application needs.
      • Research a suitable open source library on Packagist.org, the official package repository for Composer.
      • Choose the package you want to depend on.
      • Run composer require to include the dependency in the composer.json file and install the package.

      Let’s try this out with a demo application.

      The goal of this application is to transform a given sentence into a URL-friendly string – a slug. This is commonly used to convert page titles to URL paths (like the final portion of the URL for this tutorial).

      Let’s start by creating a directory for our project. We’ll call it slugify:

      • cd ~
      • mkdir slugify
      • cd slugify

      Although not required, you could now run a composer init command to create a detailed composer.json file for your project. Because our project’s only objective is to demonstrate how to install dependencies with Composer, we’ll use a simpler composer.json file that will be auto-generated when we require our first package.

      Now it’s time to search Packagist.org for a package that can help us generate slugs. If you search for the term “slug” on Packagist, you’ll get a result similar to this:

      Packagist Search Results for the term "slug"

      You’ll see two numbers on the right side of each package in the list. The number on the top represents how many times the package was installed via Composer, and the number on the bottom shows how many times a package was starred on GitHub. Generally speaking, packages with more installations and more stars tend to be more stable, since so many people are using them. It’s also important to check the package description for relevance to make sure it’s what you need.

      We need a string-to-slug converter. From the search results, the package cocur/slugify, which appears as the first result in that page, seems to be a good match, with a reasonable amount of installations and stars.

      Packages on Packagist have a vendor name and a package name. Each package has a unique identifier (a namespace) in the same format GitHub uses for its repositories: vendor/package. The library we want to install uses the namespace cocur/slugify. You need a package’s namespace in order to require it in your project.

      Now that you know exactly which package you want to install, you can run composer require to include it as a dependency and also generate the composer.json file for your project. One thing that is important to notice when requiring packages is that Composer tracks both application-level dependencies as well as system-level dependencies. System-level dependencies are important to indicate which PHP modules a package relies on. In the case of the cocur/slugify package, it requires a PHP module that we haven’t installed yet.

      When a required package relies on a system library that is currently not installed on your server, you will get an error telling which requirement is missing:

      • composer require cocur/slugify

      Output

      Using version ^4.0 for cocur/slugify ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages. Problem 1 - Installation request for cocur/slugify ^4.0 -> satisfiable by cocur/slugify[v4.0.0]. - cocur/slugify v4.0.0 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system. ...

      To solve the system dependency problem, we can search for the missing package using apt search:

      Output

      Sorting... Done Full Text Search... Done php-mbstring/focal 2:7.4+75 all MBSTRING module for PHP [default] php-patchwork-utf8/focal 1.3.1-1 all UTF-8 strings handling for PHP php7.4-mbstring/focal 7.4.3-4ubuntu1 amd64 MBSTRING module for PHP

      After locating the correct package name, you can use apt once again to install the system dependency:

      • sudo apt install php-mbstring

      Once the installation is finished, you can run the composer require command again:

      • composer require cocur/slugify

      Output

      Using version ^4.0 for cocur/slugify ./composer.json has been created Loading composer repositories with package information Updating dependencies (including require-dev) Package operations: 1 install, 0 updates, 0 removals - Installing cocur/slugify (v4.0.0): Downloading (100%) Writing lock file Generating autoload files

      As you can see from the output, Composer automatically decided which version of the package to use. If you check your project’s directory now, it will contain two new files: composer.json and composer.lock, and a vendor directory:

      Output

      total 12 -rw-rw-r-- 1 sammy sammy 59 May 4 13:56 composer.json -rw-rw-r-- 1 sammy sammy 3229 May 4 13:56 composer.lock drwxrwxr-x 4 sammy sammy 4096 May 4 13:56 vendor

      The composer.lock file is used to store information about which versions of each package are installed, and ensure the same versions are used if someone else clones your project and installs its dependencies. The vendor directory is where the project dependencies are located. The vendor folder shouldn’t be committed into version control – you only need to include the composer.json and composer.lock files.

      When installing a project that already contains a composer.json file, run composer install in order to download the project’s dependencies.

      Let’s take a quick look at version constraints. If you check the contents of your composer.json file, you’ll see something like this:

      Output

      { "require": { "cocur/slugify": "^4.0" } }

      You might notice the special character ^ before the version number in composer.json. Composer supports several different constraints and formats for defining the required package version, in order to provide flexibility while also keeping your project stable. The caret (^) operator used by the auto-generated composer.json file is the recommended operator for maximum interoperability, following semantic versioning. In this case, it defines 4.0 as the minimum compatible version, and allows updates to any future version below 5.0.

      Generally speaking, you won’t need to tamper with version constraints in your composer.json file. However, some situations might require that you manually edit the constraints–for instance, when a major new version of your required library is released and you want to upgrade, or when the library you want to use doesn’t follow semantic versioning.

      Here are some examples to give you a better understanding of how Composer version constraints work:

      ConstraintMeaningExample Versions Allowed
      ^1.0>= 1.0 < 2.01.0, 1.2.3, 1.9.9
      ^1.1.0>= 1.1.0 < 2.01.1.0, 1.5.6, 1.9.9
      ~1.0>= 1.0 < 2.0.01.0, 1.4.1, 1.9.9
      ~1.0.0>= 1.0.0 < 1.11.0.0, 1.0.4, 1.0.9
      1.2.11.2.11.2.1
      1.*>= 1.0 < 2.01.0.0, 1.4.5, 1.9.9
      1.2.*>= 1.2 < 1.31.2.0, 1.2.3, 1.2.9

      For a more in-depth view of Composer version constraints, see the official documentation.

      Next, let’s look at how to load dependencies automatically with Composer.

      Step 4 — Including the Autoload Script

      Since PHP itself doesn’t automatically load classes, Composer provides an autoload script that you can include in your project to get autoloading working for your project. This file is automatically generated by Composer when you add your first dependency.

      The only thing you need to do is include the vendor/autoload.php file in your PHP scripts before any class instantiation.

      Let’s try it out in our demo application. Open a new file called test.php in your text editor:

      Add the following code which brings in the vendor/autoload.php file, loads the cocur/slugify dependency, and uses it to create a slug:

      test.php

      <?php
      require __DIR__ . '/vendor/autoload.php';
      
      use CocurSlugifySlugify;
      
      $slugify = new Slugify();
      
      echo $slugify->slugify('Hello World, this is a long sentence and I need to make a slug from it!');
      

      Save the file and exit your editor.

      Now run the script:

      This produces the output hello-world-this-is-a-long-sentence-and-i-need-to-make-a-slug-from-it.

      Dependencies need updates when new versions come out, so let’s look at how to handle that.

      Step 5 — Updating Project Dependencies

      Whenever you want to update your project dependencies to more recent versions, run the update command:

      This will check for newer versions of the libraries you required in your project. If a newer version is found and it’s compatible with the version constraint defined in the composer.json file, Composer will replace the previous version installed. The composer.lock file will be updated to reflect these changes.

      You can also update one or more specific libraries by specifying them like this:

      • composer update vendor/package vendor2/package2

      Be sure to check in your composer.json and composer.lock files within your version control system after you update your dependencies so that others can install these newer versions too.

      Conclusion

      Composer is a powerful tool that can greatly facilitate the work of managing dependencies in PHP projects. It provides a reliable way of discovering, installing, and updating PHP packages that a project depends on. In this guide, we saw how to install Composer, how to include new dependencies in a project, and how to update these dependencies once new versions are available.



      Source link

      Установка и использование Composer в Ubuntu 18.04


      Предыдущая версия данного обучающего руководства была написана Бренненом Бернсом.

      Введение

      Composer — это популярный менеджер зависимостей PHP, который упрощает процесс установки и обновления зависимостей проекта. Он проверяет, от каких прочих пакетов зависит конкретный проект, а затем устанавливает все необходимые версии пакетов в соответствии с требованиями.

      Данное руководство поможет установить и начать работу с Composer на сервере Ubuntu 16.04.

      Предварительные требования

      Для данного обучающего руководства вам потребуется следующее:

      Шаг 1 — Установка зависимостей

      Прежде чем приступить к загрузке и установке Composer, нужно убедиться, что на сервере установлены все зависимости.

      Во-первых, необходимо обновить кэш менеджера пакетов:

      Теперь мы установим зависимости. Нам потребуется curl, чтобы загрузить Composer, и php-cli для установки и запуска. Пакет php-mbstring необходим для предоставления функций для библиотеки, которую мы будем использовать. git используется Composer для загрузки зависимостей проекта, а unzip для извлечения заархивированных пакетов. Все пакеты можно установить при помощи следующей команды:

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

      После установки всех обязательных пакетов мы можем переходить к установке Composer.

      Шаг 2 — Загрузка и установка Composer

      Composer предоставляет написанный на PHP установщик. Мы должны загрузить его, убедиться, что он не поврежден, а затем использовать его для установки Composer.

      Убедитесь, что вы находитесь в домашней директории, а затем загрузите установщик с помощью curl:

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

      Затем убедитесь, что хэш установщика совпадает с хэшем SHA-384 для последней версии установщика на странице Composer Public Keys / Signatures. Скопируйте хэш с этой страницы и сохраните его в качестве переменной командной строки:

      • HASH=544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061

      Обязательно замените последний хэш на выделенное красным значение.

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

      • php -r "if (hash_file('SHA384', 'composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

      Вы должны увидеть следующий вывод:

      Output

      Installer verified
      

      Если вы увидите Installer corrupt, вам нужно снова загрузить скрипт установки и повторно убедиться, что вы используете правильный хэш. Запустите команду и снова проверьте установщик. После успешной проверки установщика вы можете продолжить.

      Чтобы выполнить глобальную установку composer, используйте следующую команду, которая выполнит загрузку и установку Composer в качестве общесистемной команды composer в каталоге /usr/local/bin:

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

      Вывод должен выглядеть так:

      Output

      All settings correct for using Composer Downloading... Composer (version 1.6.5) successfully installed to: /usr/local/bin/composer Use it: php /usr/local/bin/composer

      Чтобы протестировать установку, запустите команду:

      Вы должны получить подобный вывод с версией и аргументами Composer.

      Output

      ______ / ____/___ ____ ___ ____ ____ ________ _____ / / / __ / __ `__ / __ / __ / ___/ _ / ___/ / /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ / ____/____/_/ /_/ /_/ .___/____/____/___/_/ /_/ Composer version 1.6.5 2018-05-04 11:44:59 Usage: command [options] [arguments] Options: -h, --help Display this help message -q, --quiet Do not output any message -V, --version Display this application version --ansi Force ANSI output --no-ansi Disable ANSI output -n, --no-interaction Do not ask any interactive question --profile Display timing and memory usage information --no-plugins Whether to disable plugins. -d, --working-dir=WORKING-DIR If specified, use the given directory as working directory. -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug . . .

      Это значит, что менеджер зависимостей Composer был успешно установлен и доступен в рамках всей системы.

      Примечание: если вы предпочитаете иметь отдельные исполняемые модули Composer для каждого проекта, который вы размещаете на этом сервере, вы можете выполнить установку локально для каждого проекта. Пользователи NPM должны быть знакомы с данным подходом. Этот метод также полезен, когда системный пользователь не имеет прав на установку программного обеспечения в рамках всей системы.

      Для этого воспользуйтесь командой php composer-setup.php​​. В результате будет сгенерирован файл composer.phar в текущей директории, который можно исполнить с помощью команды ./composer.phar.

      А теперь давайте рассмотрим использование Composer для управления

      Шаг 3 — Использование Composer в PHP проекте

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

      Чтобы использовать Composer в вашем проекте, вам потребуется файл composer.json. Файл composer.json указывает Composer, какие зависимости для вашего проекта нужно загрузить, а также какие версии каждого пакета можно использовать. Это очень важно для сохранения последовательности вашего проекта и отказа от установки нестабильных версий, которые могут вызывать проблемы с обратной совместимостью.

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

      Использование Composer для установки пакета в качестве зависимости в проект подразумевает следующие шаги:

      • Определите, какая библиотека необходима приложению.
      • Изучите подходящую библиотеку из открытого источника на Packagist.org, официальном репозитории пакетов для Composer.
      • Выберите пакет, который вы будете использовать в качестве зависимости.
      • Запустите composer require, чтобы включить зависимость в файл composer.json и установить пакет.

      Давайте попробуем сделать это на примере демо-приложения.

      Приложение преобразует указанное предложение в понятную человеку часть URL-адреса (slug). Как правило, подобные приложения используются для преобразования названия страницы в URL-адрес (например, последняя часть URL для данного обучающего руководства).

      Начнем с создания директории для нашего проекта. Мы назовем его slugify.

      • cd ~
      • mkdir slugify
      • cd slugify

      Теперь нужно найти на Packagist.org пакет, который поможет нам генерировать понятные человеку части URL-адреса. При поиске термина «slug» на Packagist вы получите примерно такой результат:

      Packagist Search: easy-slug/easy-slug, muffin/slug, ddd/slug, zelenin/slug, webcastle/slug, anomaly/slug-field_type

      Вы увидите два числа с правой стороны каждого пакета в списке. Число сверху указывает на количество установок пакета, а число внизу показывает, какие оценки пакету ставили на GitHub. Вы можете изменить порядок результатов поиска на основе этих чисел (посмотрите на два значка с правой стороны панели поиска). Как правило, пакеты с большим количеством установок и большим количеством звезд более стабильны, потому что многие люди их используют. Также важно проверить описание пакета на соответствие тому, что вам нужно.

      Нам нужен простой конвертер ​​из строки в понятную человеку часть URL-адреса. Судя по результатам поиска пакет cocur/slugify кажется наиболее подходящим вариантом с большим количеством установок и звезд (Пакет расположен ниже в результатах поиска, чем видно на скриншоте).

      Пакеты на Packagist имеют имя автора и имя пакета. Каждый пакет имеет уникальный идентификатор (пространство имен) в том же формате, который использует GitHub для своих репозиториев в форме автор/пакет. Библиотека, которую мы хотим установить, использует пространство имен cocur/slugif. Вам нужно пространство имен, чтобы использовать пакет в вашем проекте.

      Теперь, когда вы знаете, какой пакет хотите установить, запустите composer require, чтобы использовать его в качестве зависимости, а также сгенерировать файл composer.json для проекта:

      • composer require cocur/slugify

      Вы увидите следующий вывод, когда Composer загрузит зависимость:

      Output

      Using version ^3.1 for cocur/slugify ./composer.json has been created Loading composer repositories with package information Updating dependencies (including require-dev) Package operations: 1 install, 0 updates, 0 removals - Installing cocur/slugify (v3.1): Downloading (100%) Writing lock file Generating autoload files

      Как видите, Composer автоматически определил, какую версию пакета использовать. Если вы сейчас проверите каталог вашего проекта, он будет содержать два новых файла: composer.json и composer.lock, а также каталог vendor.

      Output

      total 12 -rw-rw-r-- 1 sammy sammy 59 Jul 11 16:40 composer.json -rw-rw-r-- 1 sammy sammy 2934 Jul 11 16:40 composer.lock drwxrwxr-x 4 sammy sammy 4096 Jul 11 16:40 vendor

      Файл composer.lock используется для хранения информации о том, какие версии каждого пакета установлены, а также для использования одних и тех же версий пакетов, если кто-либо будет клонировать ваш проект и устанавливать зависимости. Каталог vendor служит местом расположения зависимостей проекта. Папка vendor не обязательно будет использоваться для контроля версий, вы должны поместить туда только файлы composer.json и composer.lock.

      При установке проекта, который уже содержит файл composer.json, запустите composer install, чтобы загрузить зависимости проекта.

      Давайте быстро пробежимся по ограничениям версии. Если вы просмотрите содержимое файла composer.json, то увидите следующее:

      Output

      { "require": { "cocur/slugify": "^3.1" } } sam

      Вы можете заметить специальный символ ^ перед номером версии в файле composer.json. Composer поддерживает несколько ограничений и форматов для определения требуемой версии пакета, чтобы обеспечить гибкость и одновременно сохранить стабильность вашего проекта. Оператор карет ​​(^), используемый в автоматически генерируемом файле composer.json, рекомендуется применять для обеспечения максимальной совместимости в соответствии с семантическим управлением версиями. В данном случае он определяет 3.1 в качестве минимальной совместимой версии и позволяет обновляться до любой будущей версии ниже 4.0.

      Как правило, вам не нужно изменять ограничения версии в файле composer.json. Однако в некоторых ситуациях может потребоваться вручную отредактировать ограничения для экземпляра, например, при выходе крупного обновления требуемой библиотеки, а также в случае, когда библиотека, которую вы хотите использовать, не соответствует требованиям семантического управления версиями.

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

      ОграничениеЗначениеПример допустимых версий
      ^1.0>= 1.0 < 2.01.0, 1.2.3, 1.9.9
      ^1.1.0>= 1.1.0 < 2.01.1.0, 1.5.6, 1.9.9
      ~1.0>= 1.0 < 2.0.01.0, 1.4.1, 1.9.9
      ~1.0.0>= 1.0.0 < 1.11.0.0, 1.0.4, 1.0.9
      1.2.11.2.11.2.1
      1.*>= 1.0 < 2.01.0.0, 1.4.5, 1.9.9
      1.2. *>= 1.2 < 1.31.2.0, 1.2.3, 1.2.9

      Более подробное описание ограничений версии в Composer см. в официальной документации.

      Теперь нужно рассмотреть, как автоматически загружать зависимости с помощью Composer.

      Шаг 4 — Включение скрипта автозагрузки

      Поскольку PHP не загружает классы автоматически, Composer предоставляет скрипт автозагрузки, который можно включить в ваш проект, чтобы использовать автозагрузку бесплатно. Это значительно упрощает работу с зависимостями.

      Вам нужно будет только включить файл vendor/autoload.php в скрипты PHP перед созданием экземпляра любого класса. Composer автоматически генерирует этот файл при добавлении первой зависимости.

      Давайте попробуем сделать это в нашем приложении. Создайте файл test.php и откройте его в текстовом редакторе:

      Добавьте следующий код, который будет подключать файл vendor/autoload.php, загружать зависимость cocur/slugify и использовать ее для создания понятной человеку части URL-адреса:

      test.php

      <?php
      require __DIR__ . '/vendor/autoload.php';
      
      use CocurSlugifySlugify;
      
      $slugify = new Slugify();
      
      echo $slugify->slugify('Hello World, this is a long sentence and I need to make a slug from it!');
      

      Сохраните файл и закройте редактор.

      Запустите скрипт:

      Вы должны получить вывод hello-world-this-is-a-long-sentence-and-i-need-to-make-a-slug-from-it.

      Зависимости нуждаются в обновлениях при выходе новых версий, так что давайте рассмотрим, как решить эту проблему.

      Шаг 5 — Обновление зависимостей проекта

      Если вам нужно обновить зависимости проекта на более поздние версии, запустите команду update:

      Она будет проверять новые версии библиотек, которые требуются вам в вашем проекте. Если будет найдена новая версия, которая совместима с ограничением версии, определенным в файле composer.json, Composer заменит ранее установленную версию на новую. Файл composer.lock будет обновлен, чтобы отразить эти изменения.

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

      • composer update vendor/package vendor2/package2

      Обязательно проверьте файлы composer.json и composer.lock после обновления зависимостей, чтобы другие тоже могли установить обновленные версии.

      Заключение

      Composer — это мощный инструмент, который должен быть в арсенале каждого разработчика PHP. В этом обучающем руководстве вы установили Composer и использовали его при создании простого проекта. Теперь вы умеете устанавливать и обновлять зависимости.

      Помимо обеспечения удобного и надежного способа управления зависимостями проекта, этот инструмент задает новый стандарт для обмена и обнаружения пакетов PHP, созданных сообществом.



      Source link

      Cómo instalar y utilizar Composer en Ubuntu 18.04


      Brennen Bearnes escribió una versión anterior de este tutorial.

      Introducción

      Composer es una herramienta popular de administración de dependencias para PHP, creada principalmente para facilitar la instalación y actualización de dependencias de proyectos. Comprueba los demás paquetes de los que depende un proyecto específico y los instala utilizando las versiones apropiadas según los requisitos del proyecto.

      A través de este tutorial, instalará Composer y dará los primeros pasos con la herramienta en un sistema Ubuntu 18.04.

      Requisitos previos

      Para completar este tutorial, necesitará lo siguiente:

      Paso 1: Instalación de las dependencias

      Antes de descargar e instalar Composer, debe asegurarse de que su servidor tenga instaladas todas las dependencias.

      Primero, actualice la caché del administrador de paquetes ejecutando lo siguiente:

      A continuación, instalaremos las dependencias. Necesitaremos curl para descargar Composer y php-cli para instalarlo y ejecutarlo. El paquete php-mbstring es necesario para proporcionar funciones para una biblioteca que utilizaremos. Composer utiliza git para descargar las dependencias del proyecto y unzip para extraer paquetes comprimidos. Es posible instalar todo con el siguiente comando:

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

      Con los requisitos previos cumplidos, ya podemos instalar Composer.

      Paso 2: Descarga e instalación de Composer

      Composer ofrece un instalador escrito en PHP. Lo descargaremos, comprobaremos que no esté dañado y lo utilizaremos para instalar Composer.

      Asegúrese de posicionarse en su directorio de inicio y recupere el instalador usando curl:

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

      A continuación, verifique que el instalador coincida con el hash SHA-384 para el instalador más reciente encontrado en la página Composer Public Keys/Signatures. Copie el hash de esa página y almacénelo como variable de shell:

      • HASH=544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061

      Asegúrese de sustituir el hash más reciente por el valor resaltado.

      Ahora, ejecute el siguiente script PHP para verificar que el script de instalación se ejecute de forma segura:

      • php -r "if (hash_file('SHA384', 'composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

      Verá el siguiente resultado:

      Output

      Installer verified
      

      Si ve el mensaje Installer corrupt, tendrá que revisar nuevamente si utilizó el hash correcto y volver a descargar el script de instalación. Luego, ejecute el comando para verificar el instalador nuevamente. Una vez que cuente con un instalador verificado, podrá continuar.

      Para instalar composer de manera global, utilice el siguiente comando que lo descargará e instalará en todo el sistema como un comando llamado composer, en /usr/local/bin:

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

      Verá el siguiente resultado:

      Output

      All settings correct for using Composer Downloading... Composer (version 1.6.5) successfully installed to: /usr/local/bin/composer Use it: php /usr/local/bin/composer

      Para comprobar su instalación, ejecute lo siguiente:

      Verá que en este resultado se muestran la versión y los argumentos de Composer.

      Output

      ______ / ____/___ ____ ___ ____ ____ ________ _____ / / / __ / __ `__ / __ / __ / ___/ _ / ___/ / /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ / ____/____/_/ /_/ /_/ .___/____/____/___/_/ /_/ Composer version 1.6.5 2018-05-04 11:44:59 Usage: command [options] [arguments] Options: -h, --help Display this help message -q, --quiet Do not output any message -V, --version Display this application version --ansi Force ANSI output --no-ansi Disable ANSI output -n, --no-interaction Do not ask any interactive question --profile Display timing and memory usage information --no-plugins Whether to disable plugins. -d, --working-dir=WORKING-DIR If specified, use the given directory as working directory. -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug . . .

      Esto comprueba que Composer se instaló con éxito y está disponible en todo su sistema.

      Nota: Si prefiere tener ejecutables de Composer separados para cada proyecto que aloje en este servidor, puede instalarlos localmente para cada proyecto. Los usuarios de NPM estarán familiarizados con este enfoque. Este método también es útil cuando su usuario del sistema no tiene permisos para instalar software en todo el sistema.

      Para ello, utilice el comando php composer-setup.php. Esto generará un archivo composer.phar en su directorio actual, que puede ejecutarse con el ./composer.phar command.

      Ahora, veamos el uso de Composer para administrar dependencias.

      Paso 3: Uso de Composer en un proyecto de PHP

      Los proyectos de PHP a menudo dependen de bibliotecas externas y la administración de estas dependencias y sus versiones puede ser complicada. Composer soluciona esto haciendo un seguimiento de sus dependencias y facilitando a otros su instalación.

      Para utilizar Composer en su proyecto, necesitará un archivo composer.json. El archivo composer.json indica a Composer las dependencias que debe descargar para su proyecto y las versiones de cada paquete cuya instalación está permitida. Esto es extremadamente importante para preservar la uniformidad de su proyecto y evitar la instalación de versiones inestables que podrían causar problemas de compatibilidad con versiones anteriores.

      No necesita crear este archivo de forma manual; hay muchas probabilidades de cometer errores de sintaxis al hacerlo. Composer genera de forma automática el archivo composer.json cuando añade una dependencia a su proyecto usando el comando require. Puede añadir dependencias adicionales de la misma manera, sin la necesidad de editar manualmente este archivo.

      Para usar Composer en la instalación de un paquete como dependencia en un proyecto, se deben seguir estos pasos:

      • Identifique el tipo de biblioteca que requiere la aplicación.
      • Busque una biblioteca de código abierto adecuada  en Packagist.org, el repositorio oficial de paquetes de Composer.
      • Elija el paquete que desea usar.
      • Ejecute composer require para incluir la dependencia en el archivo composer.json e instale el paquete.

      Probemos esto con una aplicación de demostración.

      El objetivo de esta aplicación es transformar una oración en una cadena compatible con un URL; un slug. Esto se utiliza comúnmente para convertir los títulos de páginas en rutas URL (como la parte final de la URL de este tutorial).

      Comencemos creando un directorio para nuestro proyecto. Lo llamaremos slugify:

      • cd ~
      • mkdir slugify
      • cd slugify

      Ahora será el momento de buscar en Packagist.org un paquete que puede servirnos para generar slugs. Si busca el término “slug” en Packagist, obtendrá un resultado similar a este:

      Búsqueda en Packagist: easy-slug/easy-slug, muffin/slug, ddd/slug, zelenin/slug, webcastle/slug, anomaly/slug-field_type

      Observará dos números en el lado derecho de cada paquete de la lista. El número de la parte superior representa la cantidad de veces que se instaló el paquete y el de la parte inferior la cantidad de veces que se destacó un paquete en GitHub. Puede reordenar los resultados de la búsqueda conforme a estos números (busque los dos íconos del lado derecho de la barra de búsqueda). En general, los paquetes con más instalaciones y más estrellas suelen ser más estables, ya que muchas personas los utilizan. También es importante revisar la descripción del paquete para asegurarse de que se adecue a lo que usted requiere.

      Necesitamos un convertidor de string a slug simple. Conforme a los resultados de la búsqueda, el paquete cocur/slugify parece ser una buena opción al ofrecer una cantidad razonable de instalaciones y estrellas. (El paquete está un poco más abajo de lo que se muestra en la captura de pantalla de la página).

      Los paquetes en Packagist tienen un nombre de proveedor y un nombre de paquete. Cada paquete tiene un identificador único (un espacio de nombres) en el mismo formato que GitHub utiliza para sus repositorios: vendor/package. La biblioteca que deseamos instalar utiliza el espacio de nombres cocur/slugif. Necesita el espacio de nombres para solicitar el paquete en su proyecto.

      Ahora que conoce exactamente los paquetes que desea instalar, ejecute composer require para incluirlo como una dependencia y generar también el archivo composer.json para el proyecto:

      • composer require cocur/slugify

      Verá este resultado mientras Composer descarga la dependencia:

      Output

      Using version ^3.1 for cocur/slugify ./composer.json has been created Loading composer repositories with package information Updating dependencies (including require-dev) Package operations: 1 install, 0 updates, 0 removals - Installing cocur/slugify (v3.1): Downloading (100%) Writing lock file Generating autoload files

      Como se observa en el resultado, Composer automáticamente decidió la versión del paquete que utilizará. Si revisa el directorio de su proyecto, este contendrá dos nuevos archivos, composer.json y composer.lock, y un directorio vendor:

      Output

      total 12 -rw-rw-r-- 1 sammy sammy 59 Jul 11 16:40 composer.json -rw-rw-r-- 1 sammy sammy 2934 Jul 11 16:40 composer.lock drwxrwxr-x 4 sammy sammy 4096 Jul 11 16:40 vendor

      El archivo composer.lock se utiliza para almacenar información sobre las versiones de cada paquete que están instaladas y garantizar que se utilicen las mismas versiones si otra persona clona su proyecto e instala sus dependencias. En el directorio vendor se ubican las dependencias del proyecto. La carpeta vendor no requiere confirmación en el control de versión; solo debe incluir los archivos composer.json y composer.lock.

      Al instalar un proyecto que ya contenga un archivo composer.json, ejecute composer install para poder descargar las dependencias del proyecto.

      Veamos rápidamente las restricciones de versiones. Si verifica los contenidos de su archivo composer.json, verá algo parecido a lo siguiente:

      Output

      { "require": { "cocur/slugify": "^3.1" } } sam

      Posiblemente observe el carácter especial ^ antes del número de versión en composer.json. Con el fin de proporcionar flexibilidad y a su vez mantener la estabilidad de su proyecto, Composer admite diferentes restricciones y formatos para definir la versión requerida del paquete. El operador del símbolo de intercalación (^) utilizado por el archivo de generación automática composer.json es el operador recomendado para una máxima interoperabilidad, seguido del control de versión semántico. En este caso, define la versión 3.1 como la versión de compatibilidad mínima y permite actualizaciones a cualquier versión futura inferior a la 4.0.

      En general, no tendrá que alterar las restricciones de versión de su archivo composer.json. Sin embargo, en algunas situaciones posiblemente deba editar las restricciones manualmente; por ejemplo, cuando se lance una nueva versión importante de su biblioteca requerida y desee actualizarla, o cuando la biblioteca que desee utilizar no siga el control de versión semántico.

      Aquí se muestran algunos ejemplos para que comprenda mejor el funcionamiento de las restricciones de versiones de Composer:

      RestricciónSignificadoVersiones de ejemplos permitidas
      ^1.0>= 1.0 < 2.01.0, 1.2.3, 1.9.9
      ^1.1.0>= 1.1.0 < 2.01.1.0, 1.5.6, 1.9.9
      ~1.0>= 1.0 < 2.0.01.0, 1.4.1, 1.9.9
      ~1.0.0>= 1.0.0 < 1.11.0.0, 1.0.4, 1.0.9
      1.2.11.2.11.2.1
      1.*>= 1.0 < 2.01.0.0, 1.4.5, 1.9.9
      1.2. *>= 1.2 < 1.31.2.0, 1.2.3, 1.2.9

      Para acceder a una perspectiva más detallada de las restricciones de versiones de Composer, consulte la documentación oficial.

      A continuación, veamos la forma de cargar las dependencias automáticamente con Composer.

      Paso 4: Inclusión del script de carga automática

      Dado que PHP no carga automáticamente las clases, Composer proporciona un script de carga automática que puede incluir en su proyecto para acceder a la carga automática de forma gratuita. Esto facilita mucho el trabajo con sus dependencias.

      Lo único que debe hacer es incluir el archivo vendor/autoload.php en sus scripts de PHP antes de cualquier instancia de clase. Composer genera este archivo de manera automática al añadir su primera dependencia.

      Vamos a probarlo en nuestra aplicación. Cree el archivo test.php y ábralo en su editor de texto:

      Añada el siguiente código que agrega el archivo vendor/autoload.php, carga la dependencia cocur/slugify y la utiliza para crear un slug:

      test.php

      <?php
      require __DIR__ . '/vendor/autoload.php';
      
      use CocurSlugifySlugify;
      
      $slugify = new Slugify();
      
      echo $slugify->slugify('Hello World, this is a long sentence and I need to make a slug from it!');
      

      Guarde el archivo y cierre el editor.

      Ahora ejecute el script:

      El resultado de esto es hello-world-this-is-a-long-sentence-and-i-need-to-make-a-slug-from-it.

      Las dependencias necesitan actualizaciones cuando se lanzan nuevas versiones. Veamos la forma de manejar eso.

      Paso 5: Actualización de dependencias del proyecto

      Cuando desee actualizar las dependencias de proyecto a versiones más recientes, ejecute el comando update:

      Con esto, se buscarán versiones más recientes de las bibliotecas que necesitó en su proyecto. Si se encuentra una versión más reciente y es compatible con la restricción de versión definida en el archivo composer.json, Composer sustituirá la versión anterior instalada. El archivo composer.lock se actualizará para reflejar estos cambios.

      También puede actualizar una o más bibliotecas determinadas especificándolas de la siguiente manera:

      • composer update vendor/package vendor2/package2

      Después de actualizar sus dependencias, asegúrese de verificar sus archivos composer.json y composer.lock para que otros puedan instalar estas versiones más recientes.

      Conclusión

      Composer es una herramienta poderosa que todo desarrollador de PHP debe tener entre sus recursos. A través de este tutorial, instaló Composer y lo utilizó en un proyecto sencillo. De esta manera, sabrá instalar y actualizar dependencias.

      Más allá de proporcionar una alternativa sencilla y segura para gestionar las dependencias de los proyectos, también establece una nueva norma de hecho para intercambiar y descubrir paquetes PHP creados por la comunidad.



      Source link