blockify / container

Blockify 容器包。

dev-main 2024-05-16 13:57 UTC

This package is auto-updated.

Last update: 2024-09-16 14:44:22 UTC


README

简单的PHP依赖注入容器,用于WordPress插件和主题的自动绑定。

安装

composer require blockify/container

用法

PHP

首先,需要引入Composer的自动加载器,然后注册容器

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

namespace MyNamespace;

use Blockify\Container\Container;
use Blockify\Container\Registerable;

$container = new Blockify\Container\Container();

$service_providers = [
	MyServiceProvider::class      => [ __FILE__ ],
	AnotherServiceProvider::class => [],
];

foreach ( $service_providers as $service_provider => $args ) {
	$instance = $container->make( $service_provider, ...$args );

	if ( $instance instanceof Registerable ) {
		$instance->register();
	}
}

依赖项将自动解析并注入到构造函数中

namespace MyNamespace;

class MyServiceProvider {

	private string $file;

	public function __construct( string $file ) {
		$this->dependency = $dependency;
	}
	
	public function getFile(): string {
		return $this->file;
	}
}

class AnotherServiceProvider implements Registerable {

	private MyServiceProvider $my_service_provider;

	public function __construct( MyServiceProvider $my_service_provider ) {
		$this->my_service_provider = $my_service_provider;
	}
	
	public function register() {
		echo $this->my_service_provider->getFile();
	}
}