search
HomeDevelopment ToolscomposerAbout the installation and use of php-composer (simplified version)

The following tutorial column will introduce you to the installation and use of php-composer (simplified version). I hope it will be helpful to friends in need!

How to install and use php-composer (simplified version)About the installation and use of php-composer (simplified version)

Composer is a dependency management tool for PHP. It allows you to declare code libraries that your project depends on and it will install them for you in your project.
《Composer Chinese website》

2. System requirements


PHP 5.3.2 or above is required to run Composer.

Composer is multi-platform, it can run on Windows, Linux and OSX platforms at the same time.

3. Installation (ubuntu)

curl -sS https://getcomposer.org/installer | php mv composer.phar
mv composer.phar /usr/local/bin/composer

Note: If curl is not installed, you can install it through the following command
apt-get update
apt-get install curl

After your Composer is installed, you can use the following Command to see if the installation is successful

composer -v
Note If the above method fails for some reason, you can also download the installer through php:
php -r "readfile('https://getcomposer.org/installer');" | php

This will check some PHP settings and then download c

omposer.phar
to your working directory. This is the Composer binary. This is a PHAR package (PHP Archive), which is a PHP archive format that helps users perform some operations on the command line.

You can specify the Composer installation directory through the --install-dir option (it can be an absolute or relative path)

4. Use To start using Composer in your projects, you only need a

composer.json

file. This file contains the project's dependencies and other metadata.

First create a composer.json file, write the corresponding package name and version number, such as

{    
    "require": {
        "monolog/monolog": "1.13.*"
    }
}

After this, a dependent package is written, and then installed Dependency package. Get the defined dependencies to your local project, and then use Composer to run the install command in your project directory (that is, the directory where

composer.json

is located). <pre class="brush:php;toolbar:false">composer install</pre>Of course, if you are in a Windows system, you can also install dependent packages by calling the

composer.phar

package. <pre class="brush:php;toolbar:false">php composer.phar install</pre>Execute composer install to enter the automatic installation. After the installation is completed, a

composer.lock

file will be generated, which contains a specific version number. This file is required. Submit it to version management together with composer.json. Finally, when you need to update dependency packages, you can use the following command<pre class="brush:php;toolbar:false">composer update</pre>If you only want to update some dependencies

composer update monolog/monolog

5. Automatic loading

For library autoloading information, Composer generates a

vendor/autoload.php

file. You can introduce it in the entry file of your project

<?php require __DIR__ . &#39;/vendor/autoload.php&#39;;
?>

This makes it easy for you to use third-party code. For example: if your project depends on monolog, you can start using the library like this and they will be automatically loaded. <pre class="brush:php;toolbar:false">&lt;?php require __DIR__ . &amp;#39;/vendor/autoload.php&amp;#39;; $log = new Monolog\Logger(&amp;#39;name&amp;#39;); $log-&gt;pushHandler(new Monolog\Handler\StreamHandler('app.log', Monolog\Logger::WARNING)); $log-&gt;addWarning('Foo'); ?&gt;</pre>6.Packagist/Composer China Full Image

Due to wall problems, foreign images of Composer often cannot be installed normally

install

There are two ways to enable this mirroring service:

System global configuration: That is, add the configuration information to Composer's global configuration file config.json. For details, see "Method 1"

Add configuration information to the composer.json file of a project. For details, see "Method 2"
  • Method 1: Modify composer's global configuration file
  • Open the command line window (windows users) or console (Linux, Mac users) and execute the following command:
composer config -g repo.packagist composer https://packagist.phpcomposer.com
Method 2: Modify the

composer.json
configuration file of the current project:

Open the command line window (windows users) or console (Linux, Mac users) and enter In the root directory of your project (that is, the directory where the composer.json file is located), execute the following command:

composer config repo.packagist composer https://packagist.phpcomposer.com

The above command will be in the composer.json# in the current project. ## The mirror configuration information is automatically added at the end of the file (you can also add it manually):

"repositories": {
    "packagist": {
        "type": "composer",
        "url": "https://packagist.phpcomposer.com"
    }
}
7. Use autoload in Composer to automatically load the namespace

Composer can not only help you In addition to installing the required dependency packages, you can also implement the function of automatically loading the namespace. When the function libraries and class libraries we write ourselves need to be automatically loaded, we can achieve this through composer.json

. It is similar to

spl_autoload_register()

in php. In fact, if you look at the source code in Composer, you will see that its automatic loading function also uses the

spl_autoload_register() function. . "For details, please see this article for detailed introduction" We add the following code in composer.json:

{
    "autoload": {
        "psr-4": {
            "Test\\": "test/",
            "Testtwo\\": "testtwo/"
        }
    }
}

这个配置文件中有一个 autoload 段,其中有个 《PSR-4》,psr-4 是一个基于 psr-4 规则的类库自动加载对应关系,只要在其后的对象中,以 ”命名空间“: “路径” 的方式写入自己的类库信息修改完成后,之后,在执行下列命令,即可完成自动加载。

composer dumpautoload
注: "psr-4": {"Test\\": "test/"} 中的 "test/" 路径为相对于  composer.json 的路径

这个时候,你就可以调用你自己编写的函数库或者类库了

<?php require __DIR__ . &#39;/vendor/autoload.php&#39;;

$testClass = new \Test\Testclass();
?>
注:本文内容参考了《Composer 中文网》,后续还会更新 Composer 其它的实用功能

The above is the detailed content of About the installation and use of php-composer (simplified version). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Composer and AI: New Possibilities in PHP DevelopmentComposer and AI: New Possibilities in PHP DevelopmentApr 19, 2025 am 12:03 AM

The combination of AI and Composer can improve PHP development efficiency and security. Specifically reflected in: 1. Dependency analysis and optimization: AI can predict dependencies and reduce conflicts. 2. Automated security checks: AI can identify security vulnerabilities, and it is recommended to update them. 3. Code generation and optimization: AI can automatically generate and optimize related code.

Using Dicr/Yii2-Google to integrate Google API in YII2Using Dicr/Yii2-Google to integrate Google API in YII2Apr 18, 2025 am 11:54 AM

VprocesserazrabotkiveB-enclosed, Мнепришлостольностьсясзадачейтерациигооглапидляпапакробоглесхетсigootrive. LEAVALLYSUMBALLANCEFRIABLANCEFAUMDOPTOMATIFICATION, ČtookazaLovnetakProsto, Kakaožidal.Posenesko

How to use Composer to resolve JSON Schema verification issuesHow to use Composer to resolve JSON Schema verification issuesApr 18, 2025 am 11:51 AM

I'm having a tricky problem when developing a Symfony-based application: how to effectively validate JSON data format. Initially, I tried using manual verification code, but this was not only complicated, but also error-prone. After some exploration, I discovered a Composer package called ptyhard/json-schema-bundle, which brought great convenience and efficiency to my project.

Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundleUse Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundleApr 18, 2025 am 11:48 AM

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

How to quickly build Fecmall advanced project templates using ComposerHow to quickly build Fecmall advanced project templates using ComposerApr 18, 2025 am 11:45 AM

When developing an e-commerce platform, it is crucial to choose the right framework and tools. Recently, when I was trying to build a feature-rich e-commerce website, I encountered a difficult problem: how to quickly build a scalable and fully functional e-commerce platform. I tried multiple solutions and ended up choosing Fecmall's advanced project template (fecmall/fbbcbase-app-advanced). By using Composer, this process becomes very simple and efficient. Composer can be learned through the following address: Learning address

Improve Doctrine entity serialization efficiency: application of sidus/doctrine-serializer-bundleImprove Doctrine entity serialization efficiency: application of sidus/doctrine-serializer-bundleApr 18, 2025 am 11:42 AM

I had a tough problem when working on a project with a large number of Doctrine entities: Every time the entity is serialized and deserialized, the performance becomes very inefficient, resulting in a significant increase in system response time. I've tried multiple optimization methods, but it doesn't work well. Fortunately, by using sidus/doctrine-serializer-bundle, I successfully solved this problem, significantly improving the performance of the project.

Use Composer to resolve error logging issues in Laravel projectsUse Composer to resolve error logging issues in Laravel projectsApr 18, 2025 am 11:39 AM

When developing Laravel projects, the management of error logs is a very critical link. Recently, I encountered a problem in my project: how to efficiently capture and record all types of errors and ensure that these error messages can be processed in a timely manner. After some research, I found the lukeboy25/errorlogger package. It is installed through Composer and can greatly simplify the management process of error logs. You can learn composer through the following address:

How to use Composer to improve the security of Laravel applications: Applications of wiebenieuwenhuis/laravel-2fa libraryHow to use Composer to improve the security of Laravel applications: Applications of wiebenieuwenhuis/laravel-2fa libraryApr 18, 2025 am 11:36 AM

When developing a Laravel application, I encountered a common but difficult problem: how to improve the security of user accounts. With the increasing complexity of cyber attacks, a single password protection is no longer enough to ensure the security of users' data. I tried several methods, but the results were not satisfactory. Finally, I installed the wiebenieuwenhuis/laravel-2fa library through Composer and successfully added two-factor authentication (2FA) to my application, greatly improving security.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.