承接 freezemage0/discordphp-di 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

freezemage0/discordphp-di

最新稳定版本:v0.0.6

Composer 安装命令:

composer require freezemage0/discordphp-di

包简介

Wrapper around DiscordPHP that integrates DI container for event handlers

README 文档

README

Description

The package allows you to integrate DI Container with your Discord\Discord client. Your EventHandler will be automatically built in runtime whenever Event happens.

Installation

This package is available for installation via composer:

composer require freezemage0/discordphp-di

Usage

Let's say that you have an EventHandler class

<?php


class EventHandler {
    private DatabaseDriver $driver;
    private Cache $cache;
    
    public function __construct(DatabaseDriver $driver, Cache $cache)
    {
        $this->driver = $driver;
        $this->cache = $cache;
    }
    
    public function handleOnGuildJoin(): void
    {
        // your code ...     
    }
}

Now you can register your EventHandler as a handle for Discord event:

<?php

$handler = new EventHandler(
    new DatabaseDriver(),
    new Cache()
);

$discord = new \Discord\Discord();
$discord->on('GUILD_CREATE', [$handler, 'handleOnGuildJoin']);
$discord->run();

There are two major flaws in that approach:

  1. You MUST create all dependencies before creating EventHandler instance;
  2. Your EventHandler may actually never get called in a runtime but it allocates the memory anyway.

The freezemage0/discordphp-di allows you to eliminate those flaws, see below:

<?php

// Take note that in this example we will use `php-di/php-di` package.
$container = \DI\ContainerBuilder::buildDevContainer();
$builder = new \Freezemage\Discord\Builder($container);

$discord = $builder->build(); // This will instantiate Discord\Discord class!
$discord->on('GUILD_CREATE', [EventHandler::class, 'handleOnGuildJoin']);
$discord->run();

Now, your EventHandler will be instantiated (and get its dependencies resolved) only when the event is actually fired.

Integrating into already existing instance of Discord\Discord

In case you extended the Discord\Discord class in order to add your own functionality to it, you can use $builder->wrap($myDiscordInstance); to inject the container and preserve custom-defined behaviour.

$discord = new \MyProject\MyDiscord(); // extends \Discord\Discord;
$builder = new \Freezemage\Discord\Builder($container);
$discord = $builder->wrap($discord); // now $discord has Container injected with original class preserved. 

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: proprietary
  • 更新时间: 2022-08-11