Skip to content

Instantly share code, notes, and snippets.

@alganet
Created September 17, 2012 03:10
Show Gist options
  • Save alganet/3735358 to your computer and use it in GitHub Desktop.
Save alganet/3735358 to your computer and use it in GitHub Desktop.
Factories and Interfaces on Respect\Config

Factories and Interfaces on Respect\Config

Hi there! Busy day. New features on Respect\Config as well:

Factories and Builders

Respect\Config is all about managing the configuration of your objects, including which depends on which.

Sometimes in this mess, we want a lot of similar objects, from the same class or built the same way. That's why we have patterns for those cases.

Lazy loaded, persisted instances on Respect\Config are like those:

[current_date DateTime]
time = now
<?php
$container->current_date; //yay!

Not so fast :( This instance will be created just once and kept in the DI container, so it isn't that useful. Let's fix that:

[current_date new DateTime]
time = now

That new keyword makes this dependency what we really want. Note that these factories can depend on non-static objects.

Wait! =D There is more:

Interface Dependency Injection

This is my favorite. For a quite long I've been using something like this to store classes by their interfaces:

[PDO PDO]
dsn = sqlite::memory:

Then getting it like:

<?php
$pdo = $container->PDO;

This continues to work, but now we can do better:

[instanceof PDO] ;equivalent to [PDO PDO]

And also the PHP-equivalent side:

<?php
$container(new PDO('sqlite::memory:'));

And an awesome way to get those by interface in PHP:

<?php
$pdo = $container(function(PDO $conn) {
    $conn->exec('SET NAMES UTF8');
    return $conn;
});

Hope you already knew that Respect\Config is nice to manage dependencies =D

These features will be available soon on PEAR and Composer. Ask for them on @phprespect.

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