定制 mediagone/symfony-powerpack 二次开发

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

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

mediagone/symfony-powerpack

Composer 安装命令:

composer require mediagone/symfony-powerpack

包简介

Provides efficiency and code-quality helpers for Symfony.

关键字:

README 文档

README

⚠️ This project is in experimental phase, it might be subject to changes.

Latest Version on Packagist Total Downloads Software License

This package provides efficiency and code-quality helpers for Symfony:

  1. Generic param converters
  2. Primitive types parameters

Installation

This package requires PHP 7.4+

Add it as Composer dependency:

composer require mediagone/symfony-powerpack

In order to use primitive type parameters in your controllers, you must register the converters in your services.yaml by adding the following service declaration:

services:
    
    Mediagone\Symfony\PowerPack\Converters\Primitives\Services\:
        resource: '../vendor/mediagone/symfony-powerpack/src/Converters/Primitives/Services/'

1) Generic param converter

Param Converters are the best way to convert URL or route parameters into entity or Value Object instances. They allow to extract retrieval or conversion logic, preventing code duplication and keeping your controllers clean.

For more details, see Symfony's documentation.

Custom converters are very powerful, but doing Clean Code implies writing a lot of these converters. This package provides a base class that handles boilerplate code for you: you only have to define resolvers that will convert the request's parameter into the desired value.

Value Object converter

Let's take this very basic ValueObject:

final class LowercaseString
{
    private string $value;
    
    public function getValue() : string
    {
        return $this->value;
    }
    
    public function __construct(string $value)
    {
        $this->value = strtolower($value);
    }
}

You can use it in your controller by typehinting an argument:

use Mediagone\Symfony\PowerPack\Converters\Primitives\StringParam;
use Symfony\Component\Routing\Annotation\Route;

final class SearchController
{
    /**
     * @Route("/search", name="app_search")
     */
    public function __invoke(LowercaseString $searched): Response
    {
        // Return search results...
    }
}

The associated param converter only needs a single resolver to transform the value:

final class LowercaseStringParamConverter extends ValueParamConverter
{
    public function __construct()
    {
        $resolvers = [
            '' => static function(string $value) {
                return new LowercaseString($value);
            },
        ];
        
        parent::__construct(LowercaseString::class, $resolvers);
    }
    
}

The array key acts as suffix for controller's argument name, thus an empty string means that the converter will look for a request parameter with the exact same name than the controller's argument ("searched").

Note: the converters is using $request->get() internally, so it will look successively in all request data available (Route attributes, GET and POST parameters).

Entity converter

Entity converters work the exact same way, but generally imply more complexity in data retrieval. For example, you can define multiple way of getting back an User, by registering multiple resolvers in the converter:

use App\Entity\User;

final class StringParamConverter extends ValueParamConverter
{
    public function __construct(UserRepository $userRepository)
    {
        $resolvers = [
           'Id' => static function(string $value) use($userRepository) : ?User {
               return $userRepository->findById($value);
           },
           'Name' => static function(string $value) use($userRepository) : ?User {
               return $userRepository->findByName($value);
           },
        ];
        
        parent::__construct(User::class, $resolvers);
    }
    
}

This way, the converter will be able to fetch the user by Id if an userId parameter is supplied to the controller, or by its Name if the given parameter is userName. In other words, the request parameter name is the concatenation of the controller's argument name and the resolver's array key.

Again, it works the same for GET, POST or route's attributes.

use App\Entity\User;
use Symfony\Component\Routing\Annotation\Route;

final class ShowUserController
{
    /**
     * @Route("/users/{userId}", name="app_user_show")
     */
    public function __invoke(User $user): Response
    {
        // Return response...
    }
}

Optional parameters

If you need to allow a nullable argument, just make the argument nullable and handle it in your code (eg. to return a custom response):

public function __invoke(?User $user): Response
{
    if ($user === null) {
        // do something...
    }
}

Exception handling

Exceptions can be thrown in your resolvers, for example if the supplied value is not valid. In some cases, you don't need to handle those errors and you can just consider them as missing values.

You can either:

  • Enable the convertResolverExceptionsToNull option on your controller's action, to automatically handle errors and convert the parameter value to null.
  • Catch exceptions directly in the resolver, and customize the return value by yourself.

Example of @ParamConverter usage:

use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route('/api/search/{name}')
 * @ParamConverter("name", options={"convertResolverExceptionsToNull": true})
 */
public function __invoke(?LowercaseString $name): Response
{
    if ($name === null) {
        return new JsonResponse(['error' => 'Invalid or missing value for `$name` parameter.']);
    }
    
    ...
}

Note: don't forget to make your method's argument nullable!

2) Primitive types parameters

The only drawback of ParamConverters is they only work with classes but not with primitive PHP types (int, string, float...) so this package also provides a set of classes that can be used to enforce type-safety for primitive types.

Class name Parameter value example Converted PHP value
BoolParam 1 or 0 true or false
FloatParam 3.14159 3.14159
IntParam 42 42
StringParam hello 'hello'
JsonParam ["1","2","3"] ['1', '2', '3']

It also provides parameters to extract serialized arrays from the query, built from comma-separated values string :

Class name Parameter value example Converted PHP value
BoolArrayParam 1,0,1 [true, false, true]
FloatArrayParam 1.1,2.2,3.3 [1.1, 2.2, 3.3]
IntArrayParam 1,2,3 [1, 2, 3]
StringArrayParam one,two,three ['one', 'two', 'three']

Again, you only have to typehint arguments in your controller to get the request's values:

// Request URL:  /do-something?data=23&options=1,1,0

public function __invoke(IntParam $data, BoolArrayParam $options): Response
{
    $data->getValue(); // 23
    foreach ($options->getValue() as $option) {
        // ...
    }
}

License

Symfony Powerpack is licensed under MIT license. See LICENSE file.

mediagone/symfony-powerpack 适用场景与选型建议

mediagone/symfony-powerpack 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2.06k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2021 年 06 月 25 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-06-25