定制 petk/php-container 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

petk/php-container

最新稳定版本:v0.0.1

Composer 安装命令:

composer require petk/php-container

包简介

PSR-11 compatible dependency injection container

README 文档

README

Test workflow

Lightweight PSR-11 compatible PHP dependency injection container.

Installation

composer require petk/php-container

Usage

Create, for example, config/container.php file which returns container instance:

<?php

declare(strict_types=1);

use Petk\Container;

// Container instantiation.
$container = new Container();

// Adding dependencies to container is as easy as setting them to the given key.
$container->set(App\Utility::class, function ($c) {
    return new App\Utility();
});

// Adding more complex dependencies can be done like this.
$container->set(App\Database::class, function ($c) {
    return new App\Database($c->get(App\Utility::class));
});

return $container;

Then you can use such container configuration in the application front controller or other application entry files like this:

<?php

declare(strict_types=1);

// Require Composer autoloader.
require __DIR__ . '/vendor/autoload.php';

// Use the Container class.
$container = require __DIR__ . '/../config/container.php';

$database = $container->get(App\Database::class);
// Use $database further.

Circular dependencies

Circular dependencies are a bad practice where two classes have dependencies of each other. See the following example:

<?php

// ...

class ChildClass
{
    public function __construct(private ParentClass $parent)
    {
    }
}

class ParentClass
{
    public function __construct(private ChildClass $child)
    {
    }
}

$container->set(ParentClass::class, function ($c) {
    return new ParentClass($c->get(ChildClass::class));
});

$container->set(ChildClass::class, function ($c) {
    return new ChildClass($c->get(ParentClass::class));
});

// This will throw ContainerCircularDependencyException.
$object = $container->get(Parent::class);

Above will throw the ContainerCircularDependencyException which means constructing dependencies of ParentClass and ChildClass should be done differently. Perhaps you need event driven implementation here or something else.

License and contributing

Contributions are welcome by forking the repository on GitHub. This repository is released under the MIT license.

统计信息

  • 总下载量: 5
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-06-05