utopia-php/registry

一个简单的PHP依赖管理库

0.6.0 2022-07-17 15:26 UTC

README

Build Status Total Downloads Discord

Utopia Registry库是一个简单轻量级的库,用于管理PHP对象的依赖管理和懒加载初始化。这个库的目标是尽可能简单,易于学习和使用。

尽管这个库是Utopia Framework项目的一部分,但它没有依赖性,可以与其他任何PHP项目或框架独立使用。

入门指南

使用composer安装

composer require utopia-php/registry

script.php

<?php

require_once '../vendor/autoload.php';

use Utopia\Registry\Registry;

global $dbHost, $dbUser, $dbPass, $dbScheme;

$register = new Registry();

$register->set('db', function() use ($dbHost, $dbUser, $dbPass, $dbScheme) { // Register DB connection
    $pdo = new PDO("mysql:host={$dbHost};dbname={$dbScheme}", $dbUser, $dbPass, array(
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
        PDO::ATTR_TIMEOUT => 5 // Seconds
    ));

    // Connection settings
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);   // Return arrays
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);        // Handle all errors with exceptions

    return $pdo;
});

/**
 * Execute callback and create database connection only when
 *  you need it and not a second before
 */
$register->get('db');

/**
 * Second call for db service will return the instance that has been created
 *  in the previous line of code
 */
$register->get('db');

/**
 * Third call for db service when passing the value 'true' to the $fresh argument
 *  will return a fresh and new instance of the db service
 */
$register->get('db', true);

/**
 * Using the context method you can manage multiple instances of the same resources with separated scopes.
 */
$register->context('new-set-of-instances');

/**
 * You can use the 3rd parameter `$fresh` to get a new copy of the resource in every get call
 */
$register->set('time', function() { // Register DB connection
    return microtime();
}, true);

$register->get('time'); // 0.16608900
$register->get('time'); // 0.16608905

系统要求

Utopia Framework需要PHP 8或更高版本。我们建议在可能的情况下使用最新的PHP版本。

版权和许可

MIT许可(MIT)http://www.opensource.org/licenses/mit-license.php