承接 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
  • 点击次数: 1
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

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

其他信息

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