Skip to content

Instantly share code, notes, and snippets.

@mnapoli
Last active December 25, 2015 00:49
Show Gist options
  • Save mnapoli/6890585 to your computer and use it in GitHub Desktop.
Save mnapoli/6890585 to your computer and use it in GitHub Desktop.
Thoughts for PHP-DI 4.0

The point of all this is that maybe YAML should be dropped altogether in favor of PHP definitions.

YAML is less verbose, but since PHP 5.4 (short arrays) and 5.5 (short class names) it's even.

Advantages of PHP:

  • autocompletion
  • refactoring support
  • click to go to a class
  • definitions using callbacks
  • use of class constants
  • can write any PHP code (instead of a DSL like the new Symfony component)
  • use of helpers to help define dependencies (-> autocompletion and guidance)
  • no need to separate values and class definitions (in YAML, we have to since a class definitions is an array)

This is a long list…

Below is a proposition on how it could be implemented for PHP-DI 4.0. And down below would be the same config file written in YAML, for comparison purposes.

Problem: finding good class and method names for the helper methods (Definition::object…) so that they don't "pollute" too much the definitions. The shorter the better…

Suggestions:

  • Definition
  • Entry

Other problem: the new API makes doesn't allow to define "lazy" dependencies. Should it rather be something more simple (like configuring everything to be lazy, or configuring it at class level)?

<?php
// Defining an object
DI\object($className)
->constructor($arg1, $arg2)
->method('setFoo', $arg1, $arg2)
->property('bar', $value);
// Reference to an entry
DI\link($entryName);
// Defining an entry using a factory
DI\factory('create'); // calls the static method 'create' on the class
DI\factory(['MyClass', 'create']); // callback
DI\factory(function() {}); // closure
<?php
use ...;
return [
// Simple value definition
'my.value' => 123,
// Simple object definition (autowiring using Reflection if enabled)
Foo::class => DI\object(),
// Workers
'gearman.host' => 'localhost',
WorkDispatcher::class => DI\object(GearmanWorkDispatcher::class)
->constructor(DI\link('gearman.host'));
// Doctrine
'db.connection' => [
'driver' => 'mysql',
'user' => 'user',
'password' => 'password',
'dbname' => 'dbname',
'host' => 'localhost',
'driverOptions' => [
1002 => 'SET NAMES utf8',
],
],
MappingDriver::class => DI\object(YamlDriver::class)
->constructor(['models/mappers'], '.yml'),
Configuration::class => DI\factory(function (Container $c) {
$config = new Configuration();
$config->newDefaultAnnotationDriver();
$config->setMetadataDriverImpl($c->get(MappingDriver::class));
return $config;
}),
EntityManager::class => DI\factory('create')
->withArguments(DI\link('db.connection'), DI\link(Configuration::class)),
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment