Giter Club home page Giter Club logo

godfather's Introduction

Godfather

godfather A library for the strategy pattern in PHP, if you use Symfony2 you could easily integrate Godfather with the bundle.
  1. The Strategy pattern
  2. Installation
  3. Symfony2 bundle
  4. Contribution

travis-ci Latest Stable Version Total Downloads Latest Unstable Version


The Strategy Pattern

http://en.wikipedia.org/wiki/Strategy_pattern

Intent

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

TL;DR

Given an object, you want to know its service.

eg. Entity\Mug has a MugService and Entity\Tshirt has a TshirtService

$product = random(0,1)? new Entity\Mug: new Entity\Product
$productService = $godfather->getStrategy('service', $product);
// also works with
$productService = $godfather->getService($product);
echo get_class($productService);
// will be randomly TshirtService or MugService

Sandbox

A working example is at example/godfather.php

cd example
php godfather.php

When do you need a strategist as Godfather?

  • If you have a lot of classes that differs by their behaviour...
  • If you have multiple conditional statements in order to define different behaviours...
  • Given an object you want to know its manager/service/handler/provider/repository/...

Installation

composer require pugx/godfather ~0.1

A simple use case

The problem is that you have an object and you want to handle it properly.

How it works

This library does not try to duplicate the services, or to create a new container, but uses aliases in order to have a mapping between services and names.

An object is converted by the Context::getStrategyName more info at changing the Context::Converter.

The smelling code

If your code look like this you will need the godfather's protection :)

// Pseudo Code
class Cart
  function add(ProductInterface $product, OptionsInterface $options)
  {
    if ($product instanceOf Mug) {
        $item = $mugManager->add($options);
    }
    if ($product instanceOf Tshirt) {
        $item = $tshirtManager->add($options);
    }
    // ...
 }

The strategist

// Pseudo Code
class Cart
  function add(ProductInterface $product, OptionsInterface $options)
  {
    $item = $this->godfather->getManager($product)->add($options);
    // ...
 }

GodFather and an array as DIC

$container =  new Container\ArrayContainerBuilder();
$container->set('mug_service', new Your\MugService);
$container->set('tshirt_service', new Your\TshirtService);

$godfather = new Godfather($container, 'godfather');

$godfather->addStrategy('service', 'Mug', 'mug_service');
$godfather->addStrategy('service', 'Tshirt', 'tshirt_service');


// Step2. usage
class Cart
  public function __construct($godfather)
  //...
  public function add(ProductInterface $product, OptionsInterface $options)
  {
    // get the strategy for cart with the context $product
    $service = $this->godfather->getStrategy('service', $product);
    // or $strategy = $this->godfather->getCart($product);

    return $strategy->addToCart($product, $options);
 }

GodFather and Symfony Dependency Injection Container

$container =  new Container\ArrayContainerBuilder();
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.xml');

$godfather = new Godfather($container, 'godfather');

// Step2. usage
class Cart
  public function __construct($godfather)
  //...
  public function add(ProductInterface $product, OptionsInterface $options)
  {
    // get the strategy for cart with the context $product
    $service = $this->godfather->getStrategy('service', $product);
    // or $strategy = $this->godfather->getService($product);

Using the Symfony2 Bundle

Install the Bundle

Add the bundle in the app/AppKernel.php

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            ...
            new PUGX\GodfatherBundle\GodfatherBundle(),

Configuring app/config/config.yml

Minimal Configuration

# add the below configuration only if you need to specify the fallback or the interface.
godfather:
    default:
        contexts:
            manager: ~ # your strategy name

With the fallback strategy

# add the below configuration only if you need to specify the fallback or the interface.
godfather:
    default:
        contexts:
            manager:
                fallback: manager_standard  # need a reference to a defined service

Set your strategies:

parameters:
    mug.class: Mug
    tshirt.class: Tshirt

services:
    manager_standard:
        class: StandardProductManager

    manager_mug:
        class: MugManager
        tags:
            -  { name: godfather.strategy, context_name: 'manager', context_key: %mug.class% }

    manager_tshirt:
        class: TshirtManager
        tags:
            -  { name: godfather.strategy, context_name: 'manager', context_key: %tshirt.class% }

Using in the controller:

$product = new \Product\ShoeProduct();
$manager = $container->get('godfather')->getManager($product);
// or $manager = $container->get('godfather')->getStrategy('manager', $product);

// then $manager->doSomethingGreat();

Advanced with multiple instances

Instead of default you could configure your strategy in different godfather instances.

godfather:
    death:
        contexts:
            manager: ~
    life:
        contexts:
            manager: ~

the strategies:

services:
    manager.entity_life:
        class: EntityProductManager
        arguments:    ['life']
        tags:
        -  { name: godfather.strategy, instance:'life', context_name: 'manager', context_key: %product.show.class% }

    manager.entity_death:
        class: EntityProductManager
        arguments:    ['death']
        tags:
        -  { name: godfather.strategy, instance:'death', context_name: 'manager', context_key: %product.show.class% }

and then the code with multiple instances

$this->getContainer('godfather.life')->getManager($entity);
$this->getContainer('godfather.death')->getManager($entity);

Changing the Context::Converter

The Godfather\Context\Context::getStrategyName transforms an object into a strategy name, the default one just extract from the $object the short class name.

If you want another converter create your class extends the ContextInterface and then:

godfather:
    deafault:
        contexts:
            manager:
                class: \My\Context

Contribution

Active contribution and patches are very welcome. To keep things in shape we have quite a bunch of unit tests. If you're submitting pull requests please make sure that they are still passing and if you add functionality please take a look at the coverage as well it should be pretty high :)

composer create-project pugx/godfather --dev -s dev
cd godfather
bin/phpunit

License

The license is visible here.

godfather's People

Contributors

claudio-dalicandro avatar liuggio avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

godfather's Issues

Move hardcoding into configuration

In order to not recreate a new definition and use instead the alias on standard contexts, the FQCN is harcoded on non standard context.

A cleaner solution would be using the Configuration.

the defahttps://github.com/PUGX/godfather/blob/master/sf2-bundle/PUGX/GodfatherBundle/DependencyInjection/GodfatherExtension.php#L72

[sf2] improve usability

Add name as key into the dependency injection.

The goal is remove the name key from the configuration

Strategy discrimination on abstract class or interface

The context_key that works as discriminator for a strategy is a concrete class. Would it be useful extending this discrimination to abstract classes and interfaces?

services:
    manager.standard:
        class: StandardProductManager

    manager.shoe:
        class: ShoeProductManager
        tags:
            -  { name: godfather.strategy, context_name: 'manager', context_key: PUGX\CartBundle\FootWear\AbstractShoe }

thus I can treat Sneakers, HighHeels and HikingBoots with a single strategy.
Does it make sense? do you see any dangerous side effect ?

[symfony-bundle] Multiple instances

Could be great have a way to configure the bundle in order to have multiple instances of the service, this is useful when you want to separate concern.

godfather:
    death:
        contexts:
            manager:
                interface: \ABInterface
    life:
        default: true
        contexts:   
            manager: 
                interface: \ABInterface

the strategies:

services:
    manager.entity_life:
        class: EntityProductManager
       arguments:    ['life']
        tags:
            -  { name: godfather.strategy, instance:'life', context_name: 'manager', context_key: %product.show.class% }

      manager.entity_death:
        class: EntityProductManager
       arguments:    ['death']
        tags:
            -  { name: godfather.strategy, instance:'death', context_name: 'manager', context_key: %product.show.class% }

and then the code with multiple instances

$this->getContainer('godfather.life')->getManager($entity);
$this->getContainer('godfather.death')->getManager($entity);

cons

this will introduce a BC

[Symfony bundle][easy-pick] Avoid recreate another container of classes

Is very bad practice recreate the container.

Should be great if the symfony bundle could use the container of the framework, instead of a personal array of services.

The step should be:

  1. create a class that extends Godfather
  2. inject into this new class the container
  3. replacing the getStrategy with something like:
    /**
     * Get the strategy for the key ($contextName, $context).
     *
     * @param string $contextName
     * @param mixed $context
     *
     * @return mixed
     */
    public function getStrategy($contextName, $context)
    {
        $contexts = $this->getContext();
        $serviceId = $contexts[$contextName]->getStrategy($context);

        return $this->container->get($serviceId);
    }

Another option could be not inject the container and uses the getStrategy in order to retrieve the name of the service not the service itself
eg

$strategyServiceId = $this->container->get('godfather')->getStrategy('xyz', $class);
$this->container->get($strategyServiceId)->doSomething();

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.