定制 xaduken/image-symfony-support 二次开发

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

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

xaduken/image-symfony-support

Composer 安装命令:

composer require xaduken/image-symfony-support

包简介

Component for make image management in symfony very easy

README 文档

README

Description:

Component used for make one way for persist information about image to database and store them to filesystem.

Installation

composer require xaduken/image-symfony-support

Usage:

Suppose you have to entity User. This entity need to have avatar. Then you create for example Image entity and make it implements Imageable interface. In this way you guarantee Image table in database will have needle columns.

Image entity may be something like this:

<?php

namespace App\Entity;

use App\Repository\ImageRepository;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
use Xaduken\ImageSupport\EntityInterface\Imageable;

#[ORM\Entity(repositoryClass: ImageRepository::class)]
#[ORM\HasLifecycleCallbacks]
class Image implements Imageable
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 255)]
    private ?string $related_entity = null;

    #[ORM\Column(length: 400, nullable: true)]
    private ?string $path = null;

    #[ORM\Column(length: 255)]
    private ?string $fileName = null;

    #[ORM\Column(length: 255)]
    private ?string $mimeType = null;

    #[ORM\Column]
    private ?DateTimeImmutable $createdAt = null;

    #[ORM\Column]
    private ?DateTimeImmutable $updatedAt = null;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getRelatedEntity(): ?string
    {
        return $this->related_entity;
    }

    public function setRelatedEntity(string $related_entity): self
    {
        $this->related_entity = $related_entity;

        return $this;
    }

    public function getPath(): ?string
    {
        return $this->path;
    }

    public function setPath(?string $path): self
    {
        $this->path = $path;

        return $this;
    }

    public function getFileName(): ?string
    {
        return $this->fileName;
    }

    public function setFileName(string $fileName): self
    {
        $this->fileName = $fileName;

        return $this;
    }

    public function getMimeType(): ?string
    {
        return $this->mimeType;
    }

    public function setMimeType(string $mimeType): self
    {
        $this->mimeType = $mimeType;

        return $this;
    }

    public function getCreatedAt(): ?DateTimeImmutable
    {
        return $this->createdAt;
    }

    public function setCreatedAt(DateTimeImmutable $createdAt): self
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    public function getUpdatedAt(): ?DateTimeImmutable
    {
        return $this->updatedAt;
    }

    public function setUpdatedAt(DateTimeImmutable $updatedAt): self
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    #[ORM\PreUpdate]
    public function onUpdate(): void
    {
        $this->updatedAt = new DateTimeImmutable();
    }

    #[ORM\PrePersist]
    public function onCreate(): void
    {
        $this->createdAt = new DateTimeImmutable();
        $this->updatedAt = new DateTimeImmutable();
    }
}

As you can see, Image entity impelemts Imageable interface. It`s required.

After that you need to create UserImageManager and extend it by AbstractImageManager.

UserImageManager:

<?php

namespace App\Image;

use App\Entity\Image;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Xaduken\ImageSupport\Factory\ImageManagerFactoryInterface;
use Xaduken\ImageSupport\Factory\SimpleImageManagerFactory;
use Xaduken\ImageSupport\Service\AbstractImageManager;

class UserImageManager extends AbstractImageManager
{
    private EntityManagerInterface $entityManager;

    private string $targetDir;

    public function __construct(EntityManagerInterface $entityManager, string $targetDir)
    {
        $this->entityManager = $entityManager;
        $this->targetDir = $targetDir;
    }

    protected function getTargetDirectory(): string
    {
        return $this->targetDir;
    }

    protected function getRelatedClass(): string
    {
        return User::class;
    }

    protected function getImageManagerFactory(): ImageManagerFactoryInterface
    {
        return new SimpleImageManagerFactory($this->getEntityManager());
    }

    protected function getEntityManager(): EntityManagerInterface
    {
        return $this->entityManager;
    }

    protected function getImageEntityClass(): string
    {
        return Image::class;
    }
}

Let`s look more detail on methods.

getTargetDirectory()

Used for define path, where images for user should be stored. In this case we push it to constructor and transfer it via property. You may use any others way to do it.

getRelatedClass()

Push here full class name which should be stored in related_class column in table references to defined entity in getImageEntityClass method.

getImageManagerFactory()

Push here class instance of ImageManagerFactoryInterface. See full list of available factories on end of this file.

getEntityManager()

Push here doctrine entityManager. In this example we get it from constructor. In usage example we get it from dependency injection.

getImageEntityClass()

Push fully class name of entity implementation Imageable interface. In this case is Image Entity.

Testing:

After create UserImageManager we ready to store our files in database and filesystem used one simple class!

See example:

<?php

namespace App\Controller\Api;

use App\Image\UserImageManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class TestController extends AbstractController
{
    #[Route(path: '/api/test-image', name: 'test-image')]
    public function testImage(Request $request, UserImageManager $userImageManager): Response
    {
        $image = $request->files->get('image');

        $result = $userImageManager->save($image);

        dd(result);
    }
}

We get UserImageManager via dependency injection and use just one method for save image to database, filesystem and manage his relations!

But maybe you ask how UserImageManager class get $targetDirectory property? It`s very simple. just use symfony manually injection.

/config/services.yaml

parameters:
    ...
    user_image_directory: '%kernel.project_dir%/public/uploads/user'
services:
    ...
    App\Image\UserImageManager:
        arguments:
            $targetDir: '%user_image_directory%'

And that's it! Now if you need to save image related to User entity. Just get UserEntityManager by dependency injection and save your image.

Factories

This is all cool, but that if you need to resize image before save it to filesystem? All some another things? To answer this questions, I use abstract factory pattern.

If you need to define costume way for this, create your own factory, implemented by ImageManagerFactoryInterface and push your implementation to UserImageManger.getImageManagerFactory() method.

ImageManagerFactoryInterface have very simple signature, lets look

ImageManagerFactoryInterface:

<?php

namespace Xaduken\ImageSupport\Factory;

use Xaduken\ImageSupport\Database\DatabaseImageUploaderInterface;
use Xaduken\ImageSupport\Filesystem\FilesystemUploaderInterface;

interface ImageManagerFactoryInterface
{
    public function getDatabaseUploader(): DatabaseImageUploaderInterface;

    public function getFilesystemUploader(): FilesystemUploaderInterface;
}

Let`s see more detail on methods

getDatabaseUploader()

Should return class instance of implementation DatabaseImageUploaderInterface. You should create this implementation. This class should define way, how persist Imageable entity to database. For simple persisting use DatabaseImageUploader class instance.

We discuss how to create implementation of DatabaseUploaderInterface later.

getFilesystemUploader()

Should return class instance of implementation FilesystemUploaderInterface. You also should to make implementation by self or use StandardFilesystemUploader if you need simple save.

Just like with DatabaseImageUploaderInterface we discuss how to make implementation later.

DatabaseImageUploaderInterface

they signature so simple:

<?php

namespace Xaduken\ImageSupport\Database;

use Xaduken\ImageSupport\DTO\ImageInfo;
use Xaduken\ImageSupport\EntityInterface\Imageable;

interface DatabaseImageUploaderInterface
{
    public function upload(ImageInfo $imageInfo, string $relatedEntity, string $imageClass): Imageable;
}

method upload should save Image to database.

  • $imageInfo - is simple DTO class, it will be returned after save image to filesystem.
  • $relatedEntity - use it to set $relatedEntity to Imageamble entity.
  • $imageClass - create Imageable object by this property.

FilesystemUploaderInterface

they signature very familiar with DatabaseImageUploaderInterface

<?php

namespace Xaduken\ImageSupport\Filesystem;

use Symfony\Component\HttpFoundation\File\UploadedFile;
use Xaduken\ImageSupport\DTO\ImageInfo;

interface FilesystemUploaderInterface
{
    public function upload(UploadedFile $uploadedFile, string $targetDirectory): ImageInfo;
}

method upload should save image to filesystem.

  • $uploadedFile - file from symfony request
  • $targetDirectory - directory where file will be save

Method should return FileInfo DTO object, which will be used for storing into database.

And maybe you find needle realization of factory in this list:

  • SimpleImageManagerFactory - just save image to database and filesystem.

not so much right now ;)

xaduken/image-symfony-support 适用场景与选型建议

xaduken/image-symfony-support 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 7 次下载、GitHub Stars 达 1, 最近一次更新时间为 2022 年 08 月 16 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 xaduken/image-symfony-support 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-08-16