popphp / pop-loader

Pop PHP 框架的 Pop Loader 组件

3.1.1 2022-11-16 05:38 UTC

This package is auto-updated.

Last update: 2024-09-16 19:38:21 UTC


README

Build Status Coverage Status

概述

pop-loader 是用于管理应用程序自动加载的组件。如果您由于某些原因无法或不能使用 Composer,pop-loader 提供了一个具有类似特性和 API 的替代方案。它支持 PSR-4 和 PSR-0 自动加载标准。此外,如果您对提高应用程序加载速度和性能感兴趣,还支持生成和加载类映射。

pop-loaderPop PHP 框架 的一个组件。

安装

下载或克隆此存储库,并按照以下示例设置应用程序所需的自动加载。或者,您可以使用 Composer 安装 pop-loader - 我知道这很讽刺 :)

composer require popphp/pop-loader

基本用法

使用 PSR-4

假设您的应用程序包含一个名为 src 的文件夹,其中包含一个 Test 类,如下所示

app/
    src/
        Test.php
<?php
namespace MyApp;

class Test
{

}

然后,您可以创建一个自动加载对象,并将您的应用程序源注册到其中,如下所示

require_once __DIR__ . '/../src/ClassLoader.php';

$autoloader = new Pop\Loader\ClassLoader();
$autoloader->addPsr4('MyApp\\', __DIR__ . '/../app/src');

$test = new MyApp\Test();

使用 PSR-0

还支持旧的 PSR-0 标准。如果文件夹结构和类如下所示

app/
    MyApp/
        Test.php
<?php
class MyApp_Test
{

}

然后,您可以使用 PSR-0 注册它,如下所示

require_once __DIR__ . '/../src/ClassLoader.php';

$autoloader = new Pop\Loader\ClassLoader();
$autoloader->addPsr0('MyApp', __DIR__ . '/../app');

$test = new MyApp_Test();

使用类映射

要生成新的类映射

$mapper = new Pop\Loader\ClassMapper(__DIR__ . '/../app/src');
$mapper->writeToFile('classmap.php');
classmap.php
<?php

return [
    'MyApp\Foo\Bar' => '/home/nick/Projects/pop/pop-loader/app/src/Foo/Bar.php',
    'MyApp\Thing' => '/home/nick/Projects/pop/pop-loader/app/src/Thing.php',
    'MyApp\Test' => '/home/nick/Projects/pop/pop-loader/app/src/Test.php'
];

要加载现有的类映射

$autoloader = new Pop\Loader\ClassLoader();
$autoloader->addClassMapFromFile('classmap.php');