Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[DI] Add "PHP fluent format" for configuring the container#23834

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
nicolas-grekas merged 1 commit intosymfony:3.4fromnicolas-grekas:di-php-dsl
Sep 20, 2017

Conversation

nicolas-grekas
Copy link
Member

@nicolas-grekasnicolas-grekas commentedAug 8, 2017
edited
Loading

QA
Branch?3.4
Bug fix?no
New feature?yes
BC breaks?no
Deprecations?no
Tests pass?yes
Fixed tickets#22407
LicenseMIT
Doc PR-

This PR allows one to write DI configuration using just PHP, with full IDE auto-completion.
Example:

namespaceSymfony\Component\DependencyInjection\Loader\Configurator;useSymfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Foo;returnfunction (ContainerConfigurator$c) {$c->import('basic.php');$s =$c->services()->defaults()        ->public()        ->private()        ->autoconfigure()        ->autowire()        ->tag('t',array('a' =>'b'))        ->bind(Foo::class,ref('bar'))        ->private();$s->set(Foo::class)->args([ref('bar')])->public();$s->set('bar', Foo::class)->call('setFoo')->autoconfigure(false);};

vudaltsov, julienbourdeau, maks-rafalko, mickaelandrieu, Spomky, linaori, andersonamuller, sstok, luxifer, ro0NL, and 20 more reacted with thumbs up emojiinelgnu and jvasseur reacted with thumbs down emojijulienbourdeau, sstok, ro0NL, mvrhov, B-Galati, and TomasVotruba reacted with hooray emojistloyd, jvasseur, inelgnu, and pusachev reacted with confused emojidemonkoryu and TomasVotruba reacted with heart emoji
*/
function _defaults()
{
return PhpFileLoader::call(function($file, Definition $defaults) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Don't really like any of these global functions - they rely on a single container existing, and these are a big problem if there is more than one container in an app (not uncommon at all)

Copy link
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Thanks for joining :) If you look at the implementation of thePhpFileLoader::call function, it borrows the current container from the stack trace, and complains if not called in the correct context. So that there is no issues with having several containers.
Or you meant something else?
Of course, this is done for the purpose of making the DSL work, while still writting PHP. I wouldn't advocate this technique anywhere else.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Ah, I see what you mean here.

Still don't think it's a good idea. Isn't it simpler to use$this, and have thePhpFileLoader or equivalent being the current context?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

This also leads to easy auto-completion in the file itself, as you just need to add/* @var $this The\Thing */ at the top to have static analysis and autocompletion.

@nicolas-grekasnicolas-grekasforce-pushed thedi-php-dsl branch 3 times, most recently fromca4a496 to772ad9dCompareAugust 8, 2017 19:11
@nicolas-grekasnicolas-grekas changed the title[DI] Add a new "PHP fluent format" for configuring the container[DI] Add a "PHP fluent format" for configuring the containerAug 8, 2017
@nicolas-grekasnicolas-grekas changed the title[DI] Add a "PHP fluent format" for configuring the container[DI] Add "PHP fluent format" for configuring the containerAug 8, 2017
@nicolas-grekas
Copy link
MemberAuthor

(continuing#23834 (comment))

Isn't it simpler to use $this, and have the PhpFileLoader or equivalent being the current context?

Fortunately, the current context is already the PhpFileLoader instance, so$this is the correct one.
That's how I started in fact, but wasn't convinced. We can try harder. With functions, it looked nicer to me (no matter the implementation, which is not the thing I tried to optimize.)

This also leads to easy auto-completion in the file itself

don't you have auto-completion here also with the functions in the current namespace?

@Ocramius
Copy link
Contributor

don't you have auto-completion here also with the functions in the current namespace?

Yes, but with an ugly ugly hack ;-)

Just using$this is perfectly fine

@mnapoli
Copy link
Contributor

Very happy to see this,

The referenced issue was using an array-like syntax (service(MyService::class) vs [MyService::class => service()]),
but having the $id of the services while creating or loading them allows better error messages, and is required for the load() function anyway. It also requires less keystrokes.

Not sure about error messages, but the main motivation I had to write an array is that it looks more like configuration (i.e. an array of container definitions, much like a service provider). The example of a file containing method calls looks more like a script/actions.

I believe also the issue with$this stems from the fact that global function calls affect a specific container instance. With an array that problem disappears because the array is simply a list of definitions, which can then be applied to a container but the list (the array) is not tied to a specific instance. Easier to reason about IMO.

Maybe another option would be an in-between (same example as above):

namespaceSymfony\Component\DependencyInjection\Loader\PhpFileLoader;useApp\MyService;return [// loads another resourceimport('another_file.yml'),// applies to any following services_defaults()->private()->autowire()->autoconfigure(),// creates a parameter named "foo"param('foo','bar'),// creates a public service whose id<>class is "App\MyService"service(MyService::class)->public(),// loads all classes in the `../src` directory, relative to the current fileload('App\\','../src/*','../../src/{Entity,Repository}'),]

I concede it's a bit less practical to type (indentation, and don't forget the, at the end of the line) but now it looks more like a list of definitions.

And I'm biased of course but a comparison with an array indexed by ids:

namespaceSymfony\Component\DependencyInjection\Loader\PhpFileLoader;useApp\MyService;return [// loads another resourceimport('another_file.yml'),// applies to any following services_defaults()->private()->autowire()->autoconfigure(),// creates a parameter named "foo"'foo' =>'bar',// creates a public service whose id<>class is "App\MyService"    MyService::class =>service()->public(),// loads all classes in the `../src` directory, relative to the current fileload('App\\','../src/*','../../src/{Entity,Repository}'),]

Not much difference in this example except for services and parameters. In a "regular" configuration file the difference will be more striking (I especially like shortcuts like for parameters, or setting up a service for autowiring, etc.).

jvasseur reacted with thumbs up emoji

@nicolas-grekas
Copy link
MemberAuthor

@mnapoli there is a major feature that I did not emphasis enough in the description:
accurate error reporting.

All the array-like syntax can't report errors accurately. With the implementation in this PR, exceptions will report the line where the error occurred, taking the context into account (eg using a ChildDefinition with incompatible things in "_defaults".)

That's THE feature that kills array-like variants to me. Imagine the number of people that WILL do mistake and spot where in a snap. That's of paramount importance.

sstok and hhamon reacted with hooray emoji

@mnapoli
Copy link
Contributor

Current status:

capture d ecran 2017-08-08 a 23 00 16

Yep that's a good point! The file/line of the definition could be stored by playing withdebug_backtrace() but then it could be usable only in the exception message, not the exception stack trace I guess…

ragboyjr reacted with laugh emoji

@nicolas-grekasnicolas-grekasforce-pushed thedi-php-dsl branch 2 times, most recently from6ba0ba1 to1d9f16fCompareAugust 8, 2017 21:54
@linaori
Copy link
Contributor

I like the DX part ofwriting this configuration, I'm concerned about debugging though.PhpFileLoader::call() does some nasty (yet interesting) stuff which might make finding bugs a lot harder for developers that think they might have found a bug, or developers that do encounter bugs with (for example) multiple containers.@Ocramius made a valid point, if it looks like an ugly hack, it probably is an ugly hack.

I would also like to see a lot more information in the docblocks infunctions.php, as this will be the API we would be using.

While I'm not sure about the implementation, I think it's a very good step in the right direction when writing service configurations!

@ro0NL
Copy link
Contributor

ro0NL commentedAug 9, 2017
edited
Loading

Nice :) I dont really get why you prefer __call though.

About the implem. why not inverse the logic? Register the container from load() (set($container)?), and useget()? from there...

Also consider some plural functions likeimports(), aliases(), params().

Not sure about error messages, but the main motivation I had to write an array is that it looks more like configuration (i.e. an array of container definitions, much like a service provider). The example of a file containing method calls looks more like a script/actions.

Im btw in favor of the latter; no extra array boilerplate syntax.

@nicolas-grekasnicolas-grekasforce-pushed thedi-php-dsl branch 2 times, most recently from8b6272e toa4327a0CompareAugust 9, 2017 07:46
@stof
Copy link
Member

stof commentedAug 9, 2017

@ro0NL__call is used only in places where function names are using reserved keywords of PHP 5.x (which are allowed when calling functions, but not when defining them). They can be replaced by actual methods in 4.0 when dropping support for PHP 5.X.

Regarding the plural functions, this would be a pain for the returned configurator object allow further configuration.

ro0NL and Koc reacted with thumbs up emoji

@nicolas-grekasnicolas-grekasforce-pushed thedi-php-dsl branch 4 times, most recently frome72f59f tof3e1bb1CompareAugust 9, 2017 21:08
@Tobion
Copy link
Contributor

Tobion commentedAug 9, 2017
edited
Loading

I thought#23819 is the better way to go and replaces the need for this.

@Tobion
Copy link
Contributor

the whole code base is consistent with this convention

It's because there has been no variadics in php 5.3. That means we could never use new php features because it might surprise people and it's not consistent with our existing code.

Using an array, is not self-explaining at all. What does$service->args([1 => 1, 2, '$k' => 3, 'foo' => 4]) mean? And what is the error message if there is one.

linaori, Taluu, and nesl247 reacted with thumbs up emoji

@nicolas-grekas
Copy link
MemberAuthor

@Tobion if someone (you?) wants to push stronger for variadics, I'd suggest doing so in a dedicated PR, after this one (and the Routing one) have been merged, so that we can move forward.

linaori and mvrhov reacted with thumbs up emoji

@mvrhov
Copy link

👍 as Nicolas said. I'd like to start playing with this and especially with the routing one.

nicolas-grekas added a commit that referenced this pull requestSep 20, 2017
…icolas-grekas)This PR was merged into the 3.4 branch.Discussion----------[Routing] Add PHP fluent DSL for configuring routes| Q             | A| ------------- | ---| Branch?       | 3.4| Bug fix?      | no| New feature?  | yes| BC breaks?    | no| Deprecations? | no| Tests pass?   | yes| Fixed tickets | -| License       | MIT| Doc PR        | -If we add a PHP DSL for DI config (#23834), we must have a similar one for routing. Here it is. See fixtures.So, you always start with a `RoutingConfigurator $routes`, which allows you to:```php$routes->add($name, $path); // adds a route$routes->import($resource, $type = null, $ignoreErrors = false); // imports routes$routes->collection($name = ''); // starts a collection, all *names* might be prefixed```then- for "import" and "collection", you can `->prefix($path)`;- for "add" and "collection", you can fluently "add" several times;- for "collection" you add sub"`->collection()`";- and on all, you can configure the route(s) with:```php->defaults(array $defaults)->requirements(array $requirements)->options(array $options)->condition($condition)->host($pattern)->schemes(array $schemes)->methods(array $methods)->controller($controller)```Commits-------f433c9a [Routing] Add PHP fluent DSL for configuring routes
@nicolas-grekasnicolas-grekas merged commit814cc31 intosymfony:3.4Sep 20, 2017
nicolas-grekas added a commit that referenced this pull requestSep 20, 2017
…iner (nicolas-grekas)This PR was merged into the 3.4 branch.Discussion----------[DI] Add "PHP fluent format" for configuring the container| Q             | A| ------------- | ---| Branch?       | 3.4| Bug fix?      | no| New feature?  | yes| BC breaks?    | no| Deprecations? | no| Tests pass?   | yes| Fixed tickets |#22407| License       | MIT| Doc PR        | -This PR allows one to write DI configuration using just PHP, with full IDE auto-completion.Example:```phpnamespace Symfony\Component\DependencyInjection\Loader\Configurator;use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Foo;return function (ContainerConfigurator $c) {    $c->import('basic.php');    $s = $c->services()->defaults()        ->public()        ->private()        ->autoconfigure()        ->autowire()        ->tag('t', array('a' => 'b'))        ->bind(Foo::class, ref('bar'))        ->private();    $s->set(Foo::class)->args([ref('bar')])->public();    $s->set('bar', Foo::class)->call('setFoo')->autoconfigure(false);};```Commits-------814cc31 [DI] Add "PHP fluent format" for configuring the container
@nicolas-grekas
Copy link
MemberAuthor

Merged, thanks to everyone for the discussion and review, time for practice now :)

gharlan, ro0NL, Spomky, yceruto, sstok, afurculita, and OskarStark reacted with hooray emojisstok reacted with heart emoji

@nicolas-grekasnicolas-grekas deleted the di-php-dsl branchSeptember 20, 2017 13:09
@ro0NL
Copy link
Contributor

Thank you@nicolas-grekas. It's gonna be huge.

use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\ExpressionLanguage\Expression;

abstract class AbstractConfigurator
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

missing@author tag

use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;

abstract class AbstractServiceConfigurator extends AbstractConfigurator
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

missing@author tag

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

@author tags are not required.

This was referencedOct 18, 2017
chalasr added a commit that referenced this pull requestJun 28, 2023
…es_{env} with php extension (helyakin)This PR was merged into the 6.4 branch.Discussion----------[HttpKernel] when configuring the container add services_{env} with php extension| Q             | A| ------------- | ---| Branch?       | 6.4| Bug fix?      | no| New feature?  | yes| Deprecations? | no| Tickets       | none| License       | MITHello the communityThis is my first PR attempt.So after reading this [documentation](https://symfony.com/doc/current/service_container.html#remove-services) and unsuccessfully trying to load my `service_test.php`, I've noticed that the `configureContainer(..)` function in the `MicroKernelTrait` file was not configured to automatically load this file.So either we should fix the documentation, either we should fix the configuration.Since this the [framework-bundle](https://github.com/symfony/framework-bundle) is backed by [Alximy](https://alximy.io) I figured it would be cool 😎 to try and fix 🐛 the configuration.Anyway share me your thoughts about what should be done !And I wanted to say that php service configuration is 🔥 so shoutout to the one who did this (I think it's you `@nicolas`-grekas with this [PR](#23834) right ? 💪🏻)Also big thanks to `@jeremyFreeAgent` for debugging this with me and `@HeahDude` for showing me the php service configuration PR.Commits-------4aac1d9 🐛 (kernel) when configuring the container add services with php ext
symfony-splitter pushed a commit to symfony/framework-bundle that referenced this pull requestJun 28, 2023
…es_{env} with php extension (helyakin)This PR was merged into the 6.4 branch.Discussion----------[HttpKernel] when configuring the container add services_{env} with php extension| Q             | A| ------------- | ---| Branch?       | 6.4| Bug fix?      | no| New feature?  | yes| Deprecations? | no| Tickets       | none| License       | MITHello the communityThis is my first PR attempt.So after reading this [documentation](https://symfony.com/doc/current/service_container.html#remove-services) and unsuccessfully trying to load my `service_test.php`, I've noticed that the `configureContainer(..)` function in the `MicroKernelTrait` file was not configured to automatically load this file.So either we should fix the documentation, either we should fix the configuration.Since this the [framework-bundle](https://github.com/symfony/framework-bundle) is backed by [Alximy](https://alximy.io) I figured it would be cool 😎 to try and fix 🐛 the configuration.Anyway share me your thoughts about what should be done !And I wanted to say that php service configuration is 🔥 so shoutout to the one who did this (I think it's you `@nicolas`-grekas with this [PR](symfony/symfony#23834) right ? 💪🏻)Also big thanks to `@jeremyFreeAgent` for debugging this with me and `@HeahDude` for showing me the php service configuration PR.Commits-------4aac1d9fee 🐛 (kernel) when configuring the container add services with php ext
symfony-splitter pushed a commit to symfony/framework-bundle that referenced this pull requestJul 28, 2023
…es_{env} with php extension (helyakin)This PR was merged into the 6.4 branch.Discussion----------[HttpKernel] when configuring the container add services_{env} with php extension| Q             | A| ------------- | ---| Branch?       | 6.4| Bug fix?      | no| New feature?  | yes| Deprecations? | no| Tickets       | none| License       | MITHello the communityThis is my first PR attempt.So after reading this [documentation](https://symfony.com/doc/current/service_container.html#remove-services) and unsuccessfully trying to load my `service_test.php`, I've noticed that the `configureContainer(..)` function in the `MicroKernelTrait` file was not configured to automatically load this file.So either we should fix the documentation, either we should fix the configuration.Since this the [framework-bundle](https://github.com/symfony/framework-bundle) is backed by [Alximy](https://alximy.io) I figured it would be cool 😎 to try and fix 🐛 the configuration.Anyway share me your thoughts about what should be done !And I wanted to say that php service configuration is 🔥 so shoutout to the one who did this (I think it's you `@nicolas`-grekas with this [PR](symfony/symfony#23834) right ? 💪🏻)Also big thanks to `@jeremyFreeAgent` for debugging this with me and `@HeahDude` for showing me the php service configuration PR.Commits-------4aac1d9fee 🐛 (kernel) when configuring the container add services with php ext
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Reviewers

@fabpotfabpotfabpot approved these changes

@javiereguiluzjaviereguiluzjaviereguiluz left review comments

@OcramiusOcramiusOcramius left review comments

@stofstofstof left review comments

@TobionTobionTobion left review comments

@OskarStarkOskarStarkOskarStark left review comments

@ro0NLro0NLro0NL left review comments

@unkindunkindunkind left review comments

@andersonamullerandersonamullerandersonamuller left review comments

@weaverryanweaverryanweaverryan approved these changes

@ogizanagiogizanagiogizanagi approved these changes

@chalasrchalasrchalasr approved these changes

Assignees
No one assigned
Projects
None yet
Milestone
3.4
Development

Successfully merging this pull request may close these issues.

21 participants
@nicolas-grekas@Ocramius@mnapoli@linaori@ro0NL@stof@Tobion@javiereguiluz@andersonamuller@mvrhov@sstok@B-Galati@gharlan@robfrawley@weaverryan@fabpot@OskarStark@unkind@ogizanagi@chalasr@carsonbot

[8]ページ先頭

©2009-2025 Movatter.jp