funkymed/tenant-aware-bundle 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

funkymed/tenant-aware-bundle

Composer 安装命令:

composer require funkymed/tenant-aware-bundle

包简介

A Symfony bundle for multi-tenant applications

README 文档

README

Tenant Aware Bundle will help you to manage multiple configuration of your app.

The configuration come from database.

Installation

composer require funkymed/tenant-aware-bundle

create your a configuration config/packages/tenant_aware.yaml

tenant_aware:
    processors:
        - Funkymed\TenantAwareBundle\DependencyInjection\Compiler\Processor\DummyProcessor
        - Funkymed\TenantAwareBundle\DependencyInjection\Compiler\Processor\DatabaseProcessor

Modify you Kernel.php like this to use a cache by tenant

<?php

// src/Kernel.php

namespace App;

use Funkymed\TenantAwareBundle\TenantAwareKernel;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;

class Kernel extends BaseKernel
{
    use MicroKernelTrait;
    private ?string $hostname;

    public function __construct(
        string $environment,
        bool $debug,
        string $hostname
    ) {
        parent::__construct($environment, $debug);
        $this->hostname = $hostname;
    }

    public function getCacheDir(): string
    {
        if ($this->getHostname()) {
            return $this->getProjectDir().'/var/cache/'.$this->environment.'/'.$this->getHostname();
        }
        return $this->getProjectDir().'/var/cache/'.$this->environment;
    }

    public function getLogDir(): string
    {
        if ($this->getHostname()) {
            return $this->getProjectDir().'/var/log/'.$this->getHostname();
        }
        return $this->getProjectDir().'/var/log';
    }

    public function getName()
    {
        return str_replace('-', '_', $this->getHostname());
    }

    public function getKernelParameters(): array
    {
        $parameters = parent::getKernelParameters();
        $parameters['kernel.hostname'] = $this->getHostname();

        return $parameters;
    }
    public function getHostname()
    {
        $hostname = $this->getHost();
        return $hostname ? $hostname : $this->hostname;

    }
    public function getHost()
    {
        $possibleHostSources = array('HTTP_X_FORWARDED_HOST', 'HTTP_HOST', 'SERVER_NAME', 'SERVER_ADDR');
        $sourceTransformations = array(
            "HTTP_X_FORWARDED_HOST" => function ($value) {
                $elements = explode(',', $value);
                return trim(end($elements));
            }
        );
        $host = '';
        foreach ($possibleHostSources as $source) {
            if (!empty($host)) {
                break;
            }
            if (empty($_SERVER[$source])) {
                continue;
            }
            $host = $_SERVER[$source];
            if (array_key_exists($source, $sourceTransformations)) {
                $host = $sourceTransformations[$source]($host);
            }
        }

        // Remove port number from host
        $host = preg_replace('/:\d+$/', '', $host);

        return trim($host);
    }
}

and then replace bin/console with this code to make it compatible

#!/usr/bin/env php
<?php

// bin/console

use App\Kernel;
use Funkymed\TenantAwareBundle\Command\TenantAwareApplication;
use Symfony\Component\Console\Input\ArgvInput;

if (!is_dir(dirname(__DIR__).'/vendor')) {
    throw new LogicException('Dependencies are missing. Try running "composer install".');
}

if (!is_file(dirname(__DIR__).'/vendor/autoload_runtime.php')) {
    throw new LogicException('Symfony Runtime is missing. Try running "composer require symfony/runtime".');
}

require_once dirname(__DIR__).'/vendor/autoload_runtime.php';

return function (array $context) {
    $input = new ArgvInput();
    $env = $input->getParameterOption(['--env', '-e'], getenv('APP_ENV') ?: 'dev');
    $debug = getenv('APP_DEBUG') !== '0' && $env !== 'prod';

    // Added support for tenant
    $hostname = $input->getParameterOption('--tenant');

    $kernel = new Kernel($env, $debug, $hostname);
    $kernel->boot();

    return new TenantAwareApplication($kernel);

};

Now you can use the default commands of symfony but with a tenant configuration

bin/console d:d:c --tenant=localhost

The param tenant is the hostname you want to get the configuration

Configuration

Added configuration of your database in .env and config/packages/doctrine.yaml

# .env
DATABASE_HOST="localhost"
DATABASE_USER="root"
DATABASE_PASSWORD=""
DATABASE_NAME="tenant"
doctrine:
    dbal:
        driver: 'pdo_mysql'
        server_version: '8'
        use_savepoints: true
        host: '%env(resolve:DATABASE_HOST)%'
        port: 3306
        user: '%env(resolve:DATABASE_USER)%'
        password: '%env(resolve:DATABASE_URL)%'
        dbname: '%env(resolve:DATABASE_PASSWORD)%'

Create tenant database

bin/console d:d:c --if-not-exist
bin/console d:s:u -f

Add content in your database to manager different hostname (see Tenant Entity)

Add your Processor

Add more service

You can process other services than the database You could want to change an AWS S3 per hostame, or Redis, and or RabbitMQ

Just copy TenantAwareBundle/DependencyInjection/Compiler/Processor/DummyProcessor.php

And put in your DependencyInjection/Compiler/Processor namespace

Add in your processor what you want to repace

<?php

// src/DependencyInjection/DependencyInjection/Compiler/Processor/DummyProcessor.php

namespace App\DependencyInjection\Compiler\Processor;

// use this as an exemple to create your own replacement configuration
class MyProcessor extends ProcessorAbstract
{
    public function process()
    {
        // get current definition
        $definition = $this->container->getDefinition('doctrine.dbal.default_connection');
        $configuration = $definition->getArguments();

        // update it from the tenant information
        $configuration[0]["host"] = $this->tenant->getDatabaseHost();
        $configuration[0]["dbname"] = $this->tenant->getDatabaseName();
        $configuration[0]["user"] = $this->tenant->getDatabaseUser();
        $configuration[0]["password"] = $this->tenant->getDatabasePassword();

        // replace the current configuration everything is in the cache now
        $definition->replaceArgument(0, $configuration[0]);
    }
}

Update the configuration

tenant_aware:
    processors:
        - App\DependencyInjection\Compiler\Processor\MyProcessor

You can add all the processors you want.

You also can replace the Entity Tenant to put the fields you need to manage your tenants.

funkymed/tenant-aware-bundle 适用场景与选型建议

funkymed/tenant-aware-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 25 次下载、GitHub Stars 达 26, 最近一次更新时间为 2024 年 06 月 03 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「symfony」 「bundle」 「multi-tenant」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 funkymed/tenant-aware-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 funkymed/tenant-aware-bundle 我们能提供哪些服务?
定制开发 / 二次开发

基于 funkymed/tenant-aware-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

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

GitHub 信息

  • Stars: 26
  • Watchers: 5
  • Forks: 4
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-06-03