skrip42/strategy-bundle

symfony 中的 strategy

安装: 13

依赖: 0

建议者: 0

安全: 0

星星: 0

关注者: 1

分支: 0

开放问题: 0

类型:symfony-bundle

v1.0.0 2020-12-08 03:54 UTC

This package is auto-updated.

Last update: 2024-09-08 12:11:49 UTC


README

在 symfony 中实现策略和规范模式

安装

  • 运行 composer require skrip42/strategy-bundle

基本用法

策略

扩展策略管理器

namespace App\Services\Test;

use Skrip42\Bundle\StrategyBundle\StrategyManagerAbstract;

class TestStrategyManager extends StrategyManagerAbstract
{
}

实现策略接口

namespace App\Services\Test;

use Skrip42\Bundle\StrategyBundle\StrategyInterface;

abstract class TestStrategyAbstract implements StrategyInterface
{
    abstract public function doSomething();
}

创建策略

namespace App\Services\Test;

class Strategy1 extends TestStrategyAbstract
{
    public function doSomething()
    {
        .....
    }
}

class Strategy2 extends TestStrategyAbstract
{
    public function doSomething()
    {
        .....
    }
}

定义

    App\Services\Test\TestStrategyManager:
        tags: [skrip42.strategy_manager]
        properties:
          strategy:
            strategy1: App\Services\Test\Strategy1
            strategy2: App\Services\Test\Strategy2

并通过名称调用策略!

public function test(TestStrategyManager $manager): Response
{
    $strategy = $manager->get('strategy1');
    $anotherStrategy = $manager->get('strategy2');
}

规范

扩展策略管理器

namespace App\Services\Test;

use Skrip42\Bundle\StrategyBundle\StrategyManagerAbstract;

class TestSpecificationManager extends SpecificationManagerAbstract
{
}

实现策略接口

namespace App\Services\Test;

use Skrip42\Bundle\StrategyBundle\SpecificationInterface;

abstract class TestSpecificationAbstract implements SpecificationInterface
{
    abstract public function isStatisfiedBy($criteria) : bool;
    abstract public function doSomething();
}

创建策略

namespace App\Services\Test;

class Specification1 extends TestSpecificationAbstract
{
    public function isStatisfiedBy($criteria) : bool
    {
        ...check condition
    }

    public function doSomething()
    {
        .....
    }
}

class Specification2 extends TestSpecificationAbstract
{
    public function isStatisfiedBy($criteria) : bool
    {
        ...check condition
    }

    public function doSomething()
    {
        .....
    }
}

定义

    App\Services\Test\TestSpecificationManager:
        tags: [skrip42.specification_manager]
        properties:
          specification:
            strategy1: App\Services\Test\Specification1
            strategy2: App\Services\Test\Specification2

并调用规范!

public function test(TestSpecificationManager $manager): Response
{
    $specification = $manager->getFirst($condition); //get the first specification that meets the condition
    $specification = $manager->getAll($condition);   //get all specifications that meets the condition
}