定制 netbull/media-bundle 二次开发

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

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

netbull/media-bundle

Composer 安装命令:

composer require netbull/media-bundle

包简介

Media bundle

README 文档

README

A Symfony bundle for managing media — images, files and video providers (YouTube, Vimeo, Youku) — with pluggable storage (local filesystem or Amazon S3), thumbnail generation and configurable access-control strategies for downloads/views. Originally a trimmed fork of SonataMediaBundle.

  • PHP: >= 8.3
  • Symfony: 7.4 (LTS)

Installation

composer require netbull/media-bundle

Register the bundle

With Symfony Flex this is automatic. Otherwise add it to config/bundles.php:

return [
    // ...
    NetBull\MediaBundle\NetBullMediaBundle::class => ['all' => true],
];

Import the routes

The download/view endpoints live in the bundle. Add to config/routes.yaml:

netbull_media:
    resource: '@NetBullMediaBundle/config/routes.yaml'

This registers netbull_media_view (/media/view/{id}/{format}) and netbull_media_download (/media/download/{id}/{format}).

Configuration

Create config/packages/netbull_media.yaml. A minimal local-development setup:

netbull_media:
    default_context: default

    filesystem:
        local:
            directory: '%kernel.project_dir%/public/uploads/media'
            create: true

    cdn:
        server:
            path: /uploads/media

    contexts:
        default:
            providers:
                - netbull_media.provider.image
            formats:
                thumb:  { width: 150, height: 150 }
                normal: { width: 600 }

Each context declares which providers it accepts, its image formats, and the download/view security strategy. See docs/example_config.yaml for a full, annotated example (multiple contexts, S3, signed URLs, custom strategies).

Available services

Kind Service id
Providers netbull_media.provider.image, .file, .youtube, .vimeo, .youku
Filesystems netbull_media.filesystem.local, netbull_media.filesystem.s3
CDN netbull_media.cdn.server, netbull_media.cdn.local.server
Security strategies netbull_media.security.public_strategy, .forbidden_strategy, .superadmin_strategy, .connected_strategy, .hash_strategy

Upload restrictions — each provider's allowed_extensions / allowed_mime_types are enforced on upload using the file's sniffed content (not the client-supplied name/type). A file is accepted only if it matches at least one of the configured lists.

S3 ACL — default to acl: private and serve public assets through the CDN; a public-read ACL makes objects world-readable and bypasses the bundle's download/view security strategies.

Secured downloads — for contexts behind a download/view security strategy, S3-backed media is served according to the context's download.mode / view.mode:

  • stream (default) — the bytes are proxy-streamed through PHP in constant memory (lazy S3 GetObject, not the buffering Gaufrette adapter), returning a same-origin 200 so SPA clients can fetch it over XHR (no cross-origin redirect → no CORS).
  • redirect — the client is sent a short-lived (300s) pre-signed S3 URL, so the file streams S3 → client and never passes through PHP (best for large files).

Local storage always streams the file in chunks. Either way the access-control check runs in the controller before the response is issued.

Video providers (SSRF) — video providers fetch oEmbed metadata and remote thumbnails over HTTP. Thumbnail URLs are validated before fetching (http/https to public hosts only; private, loopback and cloud-metadata addresses are refused) and redirects are disabled. To route this egress through your own controls, enable framework.http_client and the bundle will use the configured client.

Thumbnail generation (sync or async)

By default thumbnails are generated in-process when the media is flushed. To offload resizing to a worker, enable the async strategy:

netbull_media:
    thumbnail:
        async: true

Optional dependency — async mode needs the Messenger component, which the bundle treats as an optional (suggested) dependency. Install it before enabling async:

composer require symfony/messenger

The message handler is only registered when symfony/messenger is installed, and enabling thumbnail.async: true without it fails fast with a clear error at container compile time. In the default sync mode the bundle works without Messenger.

When async: true, the bundle dispatches a NetBull\MediaBundle\Message\GenerateThumbnailMessage per format to the Messenger bus. Route it to an async transport so a worker does the resizing (worker recycling provides the memory isolation that long-running image processing needs):

# config/packages/messenger.yaml
framework:
    messenger:
        transports:
            async: '%env(MESSENGER_TRANSPORT_DSN)%'
        routing:
            NetBull\MediaBundle\Message\GenerateThumbnailMessage: async
php bin/console messenger:consume async --memory-limit=256M

With no transport routing configured, Messenger handles the message synchronously, so async mode is safe to enable before you have a worker.

Usage

Attach media to your entity

The bundle ships a mapped NetBull\MediaBundle\Entity\Media entity — reference it from your own entities:

use Doctrine\ORM\Mapping as ORM;
use NetBull\MediaBundle\Entity\Media;

#[ORM\ManyToOne(targetEntity: Media::class, cascade: ['persist', 'remove'])]
private ?Media $image = null;

Upload

Set the binary content and the provider/context, then persist. The bundle's Doctrine listener transforms the upload, stores it and generates thumbnails on flush:

$media = new Media();
$media->setContext('default');
$media->setProviderName('netbull_media.provider.image');
$media->setBinaryContent($uploadedFile); // Symfony UploadedFile / SplFileInfo / path

$em->persist($media);
$em->flush();

In forms, use NetBull\MediaBundle\Form\Type\MediaType (or MediaShortType) with the provider and context options.

Render in Twig

The bundle registers these Twig filters:

{# Public URL for a format #}
<img src="{{ media|path('normal') }}">

{# Signed (access-controlled) URL — image/file providers #}
<img src="{{ media|secure_path(user_identifier, 'normal') }}">

{# Rendered <img>/thumbnail markup #}
{{ media|thumbnail('thumb') }}

{# Rendered provider view (image tag, video embed, file link) #}
{{ media|view('normal') }}

Autowiring

use NetBull\MediaBundle\Provider\PoolInterface;
use NetBull\MediaBundle\Signature\SignatureHasherInterface;

public function __construct(
    private PoolInterface $pool,
    private SignatureHasherInterface $signatureHasher,
) {}

Console commands

Command Description
netbull:media:create-thumbnail <id> [format] Generate a thumbnail for one media
netbull:media:resize [context] Generate missing thumbnails
netbull:media:sync-thumbnails Regenerate thumbnails
netbull:media:clone <id> Clone a media (and its stored file)

Development

composer test        # PHPUnit
composer phpstan     # static analysis
composer cs-check    # coding standards (php-cs-fixer, dry-run)
composer check       # all of the above

License

MIT

netbull/media-bundle 适用场景与选型建议

netbull/media-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 15.79k 次下载、GitHub Stars 达 1, 最近一次更新时间为 2018 年 06 月 11 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-06-11