登录
首页 >  文章 >  php教程

如何在PHP项目中安装和使用Composer包?

来源:dev.to

时间:2024-07-19 08:21:47 367浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习文章相关编程知识。下面本篇文章就来带大家聊聊《如何在PHP项目中安装和使用Composer包?》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

如何在PHP项目中安装和使用Composer包?

在我的上一篇文章中,我解释了如何在 php 中安装和使用 composer。今天,我们将学习如何在 php 项目中安装 composer 包。我们需要安装的包是collections和 pestphp/pest.

搜索包

  • 打开浏览器并导航至 ( https://packagist.org/ )

  • 搜索收藏。向下滚动找到照明/收藏包。我们将安装这个包。

安装包

打开终端并运行composer命令来检查composer是否已安装。如果是,请运行composer search collections 来搜索集合包,并提供可用的集合包列表。然后,运行composer requireillumination/collections来安装包。

使用包

要使用包,我们必须在public目录中创建一个新文件playground.php,并添加以下代码来过滤小于或等于5的数字:

<?php
use illuminate\support\collection;
require __dir__.'/../vendor/autoload.php';

$numbers = new collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$lessthanorequalto5 = $numbers->filter(fn($number) => $number <= 5);

var_dump($lessthanorequalto5);

在终端中运行 php public/playground.php 可以看到过滤后数字的输出。

安装害虫包

要安装 pestphp/pest 包,请运行 composer search test 屏幕上显示的测试包列表,然后选择其中一个测试包。然后,运行composer require pestphp/pest --dev 将软件包安装为开发依赖项。

配置 pest 包

要配置 pest 包,请运行 phpvendor/bin/pest --init 命令。这会将composer.json 文件更新为:

{
    "name": "admin/demo",
    "authors": [
        {
            "name": "ghulam mujtaba",
            "email": "mujtabaofficial247@gmail.com"
        }
    ],
    "require": {
        "illuminate/collections": "^11.16"
    },
    "autoload": {
        "psr-4": {

            "core\\": "core/"  ,
        "http\\": "http/"          }
    
    },
    "require-dev": {
        "pestphp/pest": "^2.34"
    },
    "config": {
        "allow-plugins": {
            "pestphp/pest-plugin": true
        }
    }
}

并使用文件exampletest.php创建一个新目录tests。

<?php

test('example', function(){

    expect(true)->tobetrue();
});

运行测试

我们必须在终端中运行 phpvendor/bin/pest 命令才能看到测试文件的输出。如果将 true 替换为 false,您将看到一条错误消息。

结合测试

让我们对容器进行本地绑定测试,因为问题已经解决了。因此,重命名文件 containertest.php 并将代码替换为:

<?php
use Core\Container;
test('it can resolve something out of the container', function () {
    $container = new Container();
    $container->bind('foo', fn()=> 'foo');
    $result = $container->resolve('foo');
    expect($result)->toEqual('foo');
});

要测试在终端/提示符中再次运行 phpvendor/bin/pest 命令,它会显示输出,因为文件中没有错误

我希望你已经清楚地理解了。

终于介绍完啦!小伙伴们,这篇关于《如何在PHP项目中安装和使用Composer包?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>