Table of Contents
下载安装composer
关于composer.json文件
基本用法
自动加载
Home Development Tools composer Some learning and understanding of composer

Some learning and understanding of composer

Apr 23, 2021 pm 04:06 PM
composer laravel php

关于composer一些学习和理解

Composer 不是一个包管理器。是的,它涉及 "packages" 和 "libraries",但它在每个项目的基础上进行管理,在你项目的某个目录中(例如 vendor)进行安装。默认情况下它不会在全局安装任何东西。因此,这仅仅是一个依赖管理。

这种想法并不新鲜,Composer 受到了 node's npm 和 ruby's bundler 的强烈启发。而当时 PHP 下并没有类似的工具。

Composer 将这样为你解决问题:

  • 你有一个项目依赖于若干个库。

  • 其中一些库依赖于其他库。

  • 你声明你所依赖的东西。

  • Composer 会找出哪个版本的包需要安装,并安装它们(将它们下载到你的项目中)。

因为laravel是使用composer管理的,所以一切以laravel为基础。

下载安装composer

这里补充的是:

  1. 因为某些原因,访问国外的composer资源网站很慢,导致composer install或者update的时候经常连接超时而出错,所以改为中国镜像

    全局:
    composer config -g repo.packagist composer https://packagist.phpcomposer.com
    
    局部项目(需要在项目当前目录下执行):
    composer config repo.packagist composer https://packagist.phpcomposer.com
Copy after login

执行完命令后会在composer.json文件里面增加这段,这样就代表添加中国镜像成功了,以后执行composer install或者update之类的命令的时候就会优先使用这个镜像

    "repositories": {
      "packagist": {
        "type": "composer",
        "url": "https://packagist.phpcomposer.com"
      }
    }
Copy after login

composer selfupdate来保持composer工具本身的版本更新

关于composer.json文件

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {  //这里是告诉composer必须要安装的项目,相当于生产环境
        "php": ">=5.5.9",
        "laravel/framework": "5.2.*",  //require 需要一个 包名称,这个就是包名称
        "laravelcollective/html": "5.2.*",
        "yuanchao/laravel-5-markdown-editor": "dev-master"
    },
    "require-dev": {  //这个是开发需要安装的项目,相当于开发环境,可以通过-no-dev来取消安装这个项目里面的包
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "symfony/css-selector": "2.8.*|3.0.*",
        "symfony/dom-crawler": "2.8.*|3.0.*"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ],
        "post-install-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postInstall",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postUpdate",
            "php artisan optimize"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }
}
Copy after login

包名称的版本

确切的版本号--------1.0.2---------你可以指定包的确切版本。

范围-------->=1.0 >=1.0,<2.0 >=1.0,<1.1|>=1.2--------通过使用比较操作符可以指定有效的版本范围。 有效的运算符:>、>=、<、<=、!=。你可以定义多个范围,用逗号隔开,这将被视为一个逻辑AND处理。一个管道符号|将作为逻辑OR处理。 AND 的优先级高于 OR。

通配符--------1.0.*--------你可以使用通配符*来指定一种模式。1.0.*与>=1.0,<1.1是等效的。

赋值运算符--------~1.2--------这对于遵循语义化版本号的项目非常有用。~1.2相当于>=1.2,<2.0。
Copy after login

我们需要重点关注通配符和波浪符,通配符很好理解,波浪符有点拗口,~ 最好用例子来解释: ~1.2 相当于 >=1.2,<2.0(标记你所依赖的最低版本),而 ~1.2.3 相当于 >=1.2.3,<1.3。(指定最低版本,但允许版本号的最后一位数字上升。)语义化很难懂,但是直接看例子是可以知道怎么用的<h2 id="基本用法">基本用法</h2><p>composer是通过读取composer.json和composer.lock文件来进行安装包的</p><p>在安装依赖后,Composer 将把安装时确切的版本号列表写入 composer.lock 文件。这将锁定改项目的特定版本。<code>因为 install 命令将会检查锁文件是否存在,如果存在,它将下载指定的版本(忽略 composer.json 文件中的定义)。如果不存在 composer.lock 文件,Composer 将读取 composer.json 并创建锁文件。

一般的使用用法有:

  1. composer install  (install 命令从当前目录读取 composer.json 文件,处理了依赖关系,并把其安装到 vendor 目录下。)

  2. composer install XXXX  (这是单独安装某些包的时候使用)

  3. composer update (为了获取依赖的最新版本,并且升级 composer.lock 文件,)

  4. composer update XXX (类似)

    --prefer-source: 下载包的方式有两种: source 和 dist。对于稳定版本 composer 将默认使用 dist 方式。而 source 表示版本控制源 。如果 --prefer-source 是被启用的,composer 将从 source 安装(如果有的话)。如果想要使用一个 bugfix 到你的项目,这是非常有用的。并且可以直接从本地的版本库直接获取依赖关系。
    --prefer-dist: 与 --prefer-source 相反,composer 将尽可能的从 dist 获取,这将大幅度的加快在 build servers 上的安装。这也是一个回避 git 问题的途径,如果你不清楚如何正确的设置。
    --dry-run: 如果你只是想演示而并非实际安装一个包,你可以运行 --dry-run 命令,它将模拟安装并显示将会发生什么。
    --dev: 安装 require-dev 字段中列出的包(这是一个默认值)。
    --no-dev: 跳过 require-dev 字段中列出的包。
    --no-scripts: 跳过 composer.json 文件中定义的脚本。
    --no-plugins: 关闭 plugins。
    --no-progress: 移除进度信息,这可以避免一些不处理换行的终端或脚本出现混乱的显示。
    --optimize-autoloader (-o): 转换 PSR-0/4 autoloading 到 classmap 可以获得更快的加载支持。特别是在生产环境下建议这么做,但由于运行需要一些时间,因此并没有作为默认值。
    Copy after login
  5. composer require(require 命令增加新的依赖包到当前目录的 composer.json 文件中。但并不即可更新)

  6. composer dump-autoload(某些情况下你需要更新 autoloader,例如在你的包中加入了一个新的类。)

自动加载

composer的自动加载会生产这个文件vendor/autoload.php,然后调用这个文件就能够获得文件里面的类的自动加载

自动加载只支持 PSR-4和 PSR-0两种命名方式

Under the psr-4 key you define a mapping from namespaces to paths, relative to the package root. 

{
    "autoload": {
        "psr-4": {
            "Monolog\\": "src/",  //这里写法其实差不多,但是展现的意义并不相同,psr4会设定一个命名空间作为包的根目录,举例这行的意思是src/目录映射成为Monolog\\根目录,那么调用这个包的时候写Monolog\Bar\Baz,其实自动加载就会去这里src/Bar/Baz.php找类文件,然后加载
            "Vendor\\Namespace\\": ""
        }
    }
}

在 psr-0 key 下你定义了一个命名空间到实际路径的映射(相对于包的根目录)
{
    "autoload": {
        "psr-0": {
            "Monolog\\": "src/",  //这里的意思是src/目录映射为Monolog\\,如果要调用Monolog\Bar\Baz,那么自动加载就会去src/Monolog/Bar/Baz.php,然后加载
            "Vendor\\Namespace\\": "src/",
            "Vendor_Namespace_": "src/"
        }
    }
}
Copy after login

laravel的自动加载会多了一些东西

vendor/autoload.php

<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';  //会再次加载autoload_real.php这个文件,然后获取getLoader,不过总的过程是一样的。

return ComposerAutoloaderInitf1f9a2cafe15aa5cd52ec13394a5f5fb::getLoader();
Copy after login

引用参考:

  1. http://docs.phpcomposer.com/00-intro.html

  2. https://getcomposer.org/doc/00-intro.md


The above is the detailed content of Some learning and understanding of composer. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Apr 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:

Laravel user login function Laravel user login function Apr 18, 2025 pm 12:48 PM

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

Laravel6 actual combat video Laravel6 actual combat video Apr 18, 2025 pm 12:36 PM

To learn Laravel 6, you can get video tutorials from Laracasts (recommended), official documentation and YouTube. Recommended courses include Laracasts’ “Laravel 6 From Beginner to Mastery” and “Official Laravel 6 Tutorial” produced by the official team. When choosing a video course, consider skill level, teaching style, project experience and frequency of updates.

How to learn Laravel How to learn Laravel for free How to learn Laravel How to learn Laravel for free Apr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

How to simplify email marketing with Composer: DUWA.io's application practices How to simplify email marketing with Composer: DUWA.io's application practices Apr 18, 2025 am 11:27 AM

I'm having a tricky problem when doing a mail marketing campaign: how to efficiently create and send mail in HTML format. The traditional approach is to write code manually and send emails using an SMTP server, but this is not only time consuming, but also error-prone. After trying multiple solutions, I discovered DUWA.io, a simple and easy-to-use RESTAPI that helps me create and send HTML mail quickly. To further simplify the development process, I decided to use Composer to install and manage DUWA.io's PHP library - captaindoe/duwa.

Laravel framework skills sharing Laravel framework skills sharing Apr 18, 2025 pm 01:12 PM

In this era of continuous technological advancement, mastering advanced frameworks is crucial for modern programmers. This article will help you improve your development skills by sharing little-known techniques in the Laravel framework. Known for its elegant syntax and a wide range of features, this article will dig into its powerful features and provide practical tips and tricks to help you create efficient and maintainable web applications.

The difference between laravel and thinkphp The difference between laravel and thinkphp Apr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

See all articles