PHPackages                             pugx/godfather - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. pugx/godfather

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

pugx/godfather
==============

Strategy pattern component as library and symfony2 bundle

0.1.0(12y ago)2539.2k↓40.5%6[1 issues](https://github.com/PUGX/godfather/issues)1MITPHPPHP &gt;=5.3.0

Since Sep 9Pushed 12y ago4 watchersCompare

[ Source](https://github.com/PUGX/godfather)[ Packagist](https://packagist.org/packages/pugx/godfather)[ Docs](http://github.com/liuggio/godfather)[ RSS](/packages/pugx-godfather/feed)WikiDiscussions master Synced yesterday

READMEChangelog (3)Dependencies (3)Versions (6)Used By (1)

Godfather
=========

[](#godfather)

[![godfather](https://camo.githubusercontent.com/5e9ce60986a52006f3e9432fd5f8c536ee24fcbdd6bedc8ac3124f4d0dfc4ebb/687474703a2f2f696d616765732e77696b69612e636f6d2f63796265726e6174696f6e732f696d616765732f617263686976652f632f63392f323030373130303830343335353721476f646661746865725f68616e645f626c61636b2e706e67)](https://camo.githubusercontent.com/5e9ce60986a52006f3e9432fd5f8c536ee24fcbdd6bedc8ac3124f4d0dfc4ebb/687474703a2f2f696d616765732e77696b69612e636f6d2f63796265726e6174696f6e732f696d616765732f617263686976652f632f63392f323030373130303830343335353721476f646661746865725f68616e645f626c61636b2e706e67)A library for the strategy pattern in PHP, if you use Symfony2 you could easily integrate Godfather with the bundle.1. [The Strategy pattern](#the-strategy-pattern)
2. [Installation](#how-it-works)
3. [Symfony2 bundle](#using-the-symfony2-bundle)
4. [Contribution](#contribution)

[![travis-ci](https://camo.githubusercontent.com/8fd3cd099808c603f9512436854393715226152a8d4d25f915e7872b8cd2fc6f/68747470733a2f2f7365637572652e7472617669732d63692e6f72672f505547582f676f646661746865722e706e67)](http://travis-ci.org/PUGX/godfather) [![Latest Stable Version](https://camo.githubusercontent.com/7ab8bd6e111aeff6b9e505aac8a320aa1a4f05c4a99c1384de32fca48c89c2ab/68747470733a2f2f706f7365722e707567782e6f72672f505547582f676f646661746865722f762f737461626c652e706e67)](https://packagist.org/packages/PUGX/godfather) [![Total Downloads](https://camo.githubusercontent.com/fda737a4d7ff943f661bd0fbffb453e6b558ec13bb6e72c056f2d2d89b58d113/68747470733a2f2f706f7365722e707567782e6f72672f505547582f676f646661746865722f646f776e6c6f6164732e706e67)](https://packagist.org/packages/PUGX/godfather) [![Latest Unstable Version](https://camo.githubusercontent.com/1904adeb290b6765156befa5dbd7189cf618ace620237ba8e448f86c2834f384/68747470733a2f2f706f7365722e707567782e6f72672f505547582f676f646661746865722f762f756e737461626c652e706e67)](https://packagist.org/packages/PUGX/godfather)

---

The Strategy Pattern
--------------------

[](#the-strategy-pattern)

[http://en.wikipedia.org/wiki/Strategy\_pattern](http://en.wikipedia.org/wiki/Strategy_pattern)

### Intent

[](#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
-----

[](#tldr)

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
-------

[](#sandbox)

A working example is at [example/godfather.php](example/godfather.php)

```
cd example
php godfather.php

```

When do you need a strategist as Godfather?
-------------------------------------------

[](#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
------------

[](#installation)

`composer require pugx/godfather ~0.1`

A simple use case
-----------------

[](#a-simple-use-case)

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

How it works
------------

[](#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](#changing-the-contextconverter).

### The smelling code

[](#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

[](#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

[](#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

[](#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
-------------------------

[](#using-the-symfony2-bundle)

### Install the 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`

[](#configuring-appconfigconfigyml)

#### Minimal Configuration

[](#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

[](#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:

[](#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:

[](#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

[](#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

[](#changing-the-contextconverter)

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
------------

[](#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
-------

[](#license)

[The license is visible here](LICENSE).

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity38

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 91.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~67 days

Total

3

Last Release

4547d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/446a646f719434553ab25f0f931d28ec09fbb036528126ac7e9d54a2e8132581?d=identicon)[liuggio](/maintainers/liuggio)

---

Top Contributors

[![liuggio](https://avatars.githubusercontent.com/u/530406?v=4)](https://github.com/liuggio "liuggio (43 commits)")[![claudio-dalicandro](https://avatars.githubusercontent.com/u/2378579?v=4)](https://github.com/claudio-dalicandro "claudio-dalicandro (4 commits)")

---

Tags

bundlelibraryStrategy Pattern

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/pugx-godfather/health.svg)

```
[![Health](https://phpackages.com/badges/pugx-godfather/health.svg)](https://phpackages.com/packages/pugx-godfather)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
