Skip to content

Instantly share code, notes, and snippets.

@sukei
Last active April 20, 2022 08:44
Show Gist options
  • Save sukei/9093311 to your computer and use it in GitHub Desktop.
Save sukei/9093311 to your computer and use it in GitHub Desktop.
A Service Container in a Tweet
<?php
/**
* The Container class is a lightweight service container.
*
* ...and it fits in a tweet.
*
* @author Quentin Schuler aka Sukei <[email protected]>
*/
class Container{private $s;function set($k,$c){$this->s[$k]=$c;}function get($k){return(is_a($v=$this->s[$k],'Closure'))?$v($this):$v;}}
@sukei
Copy link
Author

sukei commented Feb 19, 2014

<?php

class Mailer
{
    private $transport;

    public function __construct($transport)
    {
        $this->transport = $transport;

        // ...
    }
}
<?php

class NewsletterManager
{
    private $mailer;

    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;

        // ...
    }
}
<?php

$container = new Container();

$container->set('mailer.class', 'Mailer');
$container->set('mailer.transport', 'sendmail');
$container->set('mailer', function(Container $container) {
    $class = $container->get('mailer.class');

    return new $class($container->get('mailer.transport'));
});

$container->set('newsletter_manager.class', 'NewsletterManager');
$container->set('newsletter_manager', function(Container $container) {
    $class = $container->get('newsletter_manager.class');

    return new $class($container->get('mailer'));
});

$manager = $container->get('newsletter_manager');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment