bulldog/container

v1.2.0 2018-08-12 23:27 UTC

This package is auto-updated.

Last update: 2024-09-05 19:33:57 UTC


README

Travis (.org) branch Coveralls github Packagist Packagist

API 文档.

别名,狗屋。此容器实现了PSR-11ArrayAccess

安装

composer require bulldog/container

用法

在尝试获取该条目之前,您应该检查容器中是否有对该ID的条目。

键 / 值

<?php
include 'vendor/autoload.php';

$container = new Bulldog\Container;

$value = $container->set('id', 'value');
echo $value;
// value

$result = $container->has('id');
var_dump($result);
// bool(true)

$value = $container->get('id');
echo $value;
// value

键 / 闭包

如果与键关联的值是可调用,则容器会为您调用它,并返回闭包的内容。这允许您懒加载类或服务。

<?php
include 'vendor/autoload.php';

$container = new Bulldog\Container;

class Example
{
    public function test()
    {
        echo 'it works!';
    }

}

// Using a closure
$container['service'] = function() {
    return new Example;
};

$service = $container['service'];
$service->test();
// it works!

// Storing an object (not lazy loaded)
$container['service'] = new Example;
$service = $container['service'];
$service->test();
// it works!

依赖注入容器

<?php

include 'vendor/autoload.php';

$container = new Bulldog\Container;

class Required
{
    private $test = "Hello";

    public function getTest()
    {
        return $this->test;
    }
}

class Example
{
    private $required;

    public function __construct(Required $required)
    {
        $this->required = $required;
    }

    public function run()
    {
        echo $this->required->getTest();
    }

}
$container['required'] = function() {
    return new Required;
};

$container['example'] = function($c) {
    return new Example($c['required']);
};

$e = $container['example'];
$e->run();

可用方法

所有参数都是必需的。

用户不应将容器传递给对象,以便对象可以检索其自己的依赖项。请参阅PHP-FIG提供的Meta 文档

贡献

欢迎所有贡献!如果有问题,请首先创建一个问题,并告诉我们您是否打算修复它。然后分支仓库,创建一个新的分支,并针对问题进行工作。分支名称应与问题相关。

风格

使用默认规则运行php-cs-fixer

php-cs-fixer fix ./src
php-cs-fixer fix ./tests