Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Lazy services are not shared #27756

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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
yellow1912 opened this issue Jun 28, 2018 · 9 comments
Closed

Lazy services are not shared #27756

yellow1912 opened this issue Jun 28, 2018 · 9 comments

Comments

@yellow1912
Copy link

yellow1912 commented Jun 28, 2018

Symfony version(s) affected: 3.4.12

Description

I'm not sure if this is intentional or a new issue that has just come up, but it seems like any service that is declared as lazy is not shared anymore.

How to reproduce
Declare any service as lazy and then call it more than once any where, you will see that it is initialized more than once (__construct is called many times)

This issue happens today after I updated my code.

Edit: I tested on a very class with nothing but the __construct and another simple method, I can confirm that this happens on my current installation. If further checking is needed I can try with a barebone installation of Symfony.

@nicolas-grekas
Copy link
Member

I didn't manage to reproduce following the description. Would you be able to provide a repository with a reproducer?

@dmaicher
Copy link
Contributor

@nicolas-grekas
Copy link
Member

Also, what's the output of composer show on your app?

@yellow1912
Copy link
Author

Below is my composer show result, Im going to install a bare version of SF to see as well:

abraham/twitteroauth                  dev-master dac8b25  The most popular PHP library for use with the Twitter OAuth REST API.
aws/aws-sdk-php                       3.62.4              AWS SDK for PHP - Use Amazon Web Services in your PHP project
beberlei/DoctrineExtensions           v1.0.23             A set of extensions to Doctrine 2 that add support for additional query functions available in MySQL and Oracle.
behat/gherkin                         v4.5.1              Gherkin DSL parser for PHP 5.3
behat/transliterator                  v1.2.0              String transliterator
clue/stream-filter                    v1.4.0              A simple and modern approach to stream filtering in PHP
codeception/codeception               2.4.3               BDD-style testing framework
codeception/phpunit-wrapper           6.0.10              PHPUnit classes used by Codeception
codeception/stub                      2.0.1               Flexible Stub wrapper for PHPUnit's Mock Builder
composer/ca-bundle                    1.1.1               Lets you find a path to the system CA bundle, and includes a fallback to the Mozilla CA bundle.
composer/composer                     1.0.0-alpha11       Composer helps you declare, manage and install dependencies of PHP projects, ensuring you have the right stack everywhere.
composer/semver                       1.4.2               Semver library that offers utilities, version constraint parsing and validation.
composer/spdx-licenses                1.4.0               SPDX licenses list and validation library.
craue/config-bundle                   1.4.2               Database-stored settings made available via a service for your Symfony project.
dcarbone/curl-header-extractor        2.0.3               Utility to extract headers from PHP CURL to file request.
dcarbone/php-consul-api               0.3.10              PHP client implementation for the Consul API
dcarbone/php-consul-api-bundle        0.5.2               Bundle to enable usage of dcarbone/php-consul-api inside of a Symfony 3 project
defuse/php-encryption                 dev-master 0d4d27c  Secure PHP Encryption Library
dirkgroenen/pinterest-api-php         dev-master 2dcffb7  PHP Wrapper for the official Pinterest API
doctrine/annotations                  v1.6.0              Docblock Annotations Parser
doctrine/cache                        dev-master 6cf8900  Caching library offering an object-oriented API for many cache backends
doctrine/collections                  v1.5.0              Collections Abstraction library
doctrine/common                       v2.8.1              Common Library for Doctrine projects
doctrine/dbal                         v2.7.1              Database Abstraction Layer
doctrine/doctrine-bundle              1.9.1               Symfony DoctrineBundle
doctrine/doctrine-cache-bundle        dev-master df9c9e9  Symfony Bundle for Doctrine Cache
doctrine/doctrine-migrations-bundle   v1.3.1              Symfony DoctrineMigrationsBundle
doctrine/inflector                    v1.3.0              Common String Manipulations with regard to casing and singular/plural rules.
doctrine/instantiator                 1.1.0               A small, lightweight utility to instantiate objects in PHP without invoking their constructors
doctrine/lexer                        v1.0.1              Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers.
doctrine/migrations                   v1.8.1              Database Schema migrations using Doctrine DBAL
doctrine/orm                          v2.6.1              Object-Relational-Mapper for PHP
dragonmantank/cron-expression         v2.2.0              CRON for PHP: Calculate the next or previous run date and determine if a CRON expression is due
egulias/email-validator               2.1.4               A library for validating emails against several RFCs
elasticsearch/elasticsearch           v5.3.2              PHP Client for Elasticsearch
facebook/graph-sdk                    5.6.2               Facebook SDK for PHP
facebook/webdriver                    1.6.0               A PHP client for Selenium WebDriver
fig/link-util                         1.0.0               Common utility implementations for HTTP links
firebase/php-jwt                      v5.0.0              A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.
flowjs/flow-php-server                v1.0.3              PHP library for handling chunk uploads. Works with flow.js html5 file uploads.
friendsofsymfony/jsrouting-bundle     1.6.3               A pretty nice way to expose your Symfony2 routing to client applications.
friendsofsymfony/oauth-server-bundle  1.6.1               Symfony2 OAuth Server Bundle
friendsofsymfony/oauth2-php           1.2.3               OAuth2 library
fzaninotto/faker                      v1.7.1              Faker is a PHP library that generates fake data for you.
gedmo/doctrine-extensions             v2.4.x-dev 0b7bdbe  Doctrine2 behavioral extensions
giggsey/libphonenumber-for-php        8.9.9               PHP Port of Google's libphonenumber
giggsey/locale                        1.5                 Locale functions required by libphonenumber-for-php
google/apiclient                      v2.2.2              Client library for Google APIs
google/apiclient-services             v0.63               Client library for Google APIs
google/auth                           v1.3.0              Google Auth Library for PHP
guzzlehttp/guzzle                     6.3.3               Guzzle is a PHP HTTP client library
guzzlehttp/promises                   v1.3.1              Guzzle promises library
guzzlehttp/psr7                       1.4.2               PSR-7 message implementation that also provides common utility methods
guzzlehttp/ringphp                    1.1.0               Provides a simple API and specification that abstracts away the details of HTTP into a single PHP function.
guzzlehttp/streams                    3.0.0               Provides a simple abstraction over streams of data
hamcrest/hamcrest-php                 v1.2.2              This is the PHP port of Hamcrest Matchers
happyr/linkedin-api-client            dev-master 58bb3bc  LinkedIn API client. Handles OAuth, CSRF protection. Easy to implement and extend. This is a standalone library for any composer project.
http-interop/http-factory             0.3.0               Common interface for HTTP message factories
hwi/oauth-bundle                      0.5.3               Support for authenticating users using both OAuth1.0a and OAuth2 in Symfony2.
jdorn/sql-formatter                   v1.2.17             a PHP SQL highlighting library
jippi/vault-php-sdk                   2.0.0               SDK to talk with vaultproject.io API
jms/aop-bundle                        1.3.0               Adds AOP capabilities to Symfony2
jms/cg                                1.2.0               Toolset for generating PHP code
jms/di-extra-bundle                   1.9.2               Allows to configure dependency injection using annotations
jms/metadata                          1.6.0               Class/method/property metadata management in PHP
jms/translation-bundle                dev-master 4d9c8a0  Puts the Symfony Translation Component on steroids
justinrainbow/json-schema             1.6.1               A library to validate a json schema.
knplabs/knp-components                dev-master 8e33ffb  Knplabs component library
knplabs/knp-paginator-bundle          dev-master f4ece5b  Paginator bundle for Symfony to automate pagination and simplify sorting and other features
kriswallsmith/assetic                 v1.4.0              Asset Management for PHP
kriswallsmith/buzz                    v0.17.1             Lightweight HTTP client
league/commonmark                     dev-master f18ebbe  Markdown parser for PHP based on the CommonMark spec
league/flysystem                      1.0.45              Filesystem abstraction: Many filesystems, one API.
league/flysystem-aws-s3-v3            1.0.19              Flysystem adapter for the AWS S3 SDK v3.x
league/flysystem-cached-adapter       dev-master 60d73d9  An adapter decorator to enable meta-data caching.
league/oauth2-client                  2.3.0               OAuth 2.0 Client Library
league/oauth2-facebook                dev-master bcbcd54  Facebook OAuth 2.0 Client Provider for The PHP League OAuth2-Client
misd/phone-number-bundle              dev-master d5213c6  Integrates libphonenumber into your Symfony2 application
mockery/mockery                       0.9.9               Mockery is a simple yet flexible PHP mock object framework for use in unit testing with PHPUnit, PHPSpec or any other testing framework. Its cor...
moneyphp/money                        v3.1.3              PHP implementation of Fowler's Money pattern
monolog/monolog                       1.23.0              Sends your logs to files, sockets, inboxes, databases and various web services
mtdowling/jmespath.php                2.4.0               Declaratively specify how to extract elements from a JSON document
mustangostang/spyc                    0.6.2               A simple YAML loader/dumper class for PHP
myclabs/deep-copy                     1.8.1               Create deep copies (clones) of your objects
nelmio/alice                          1.x-dev 39d05bc     Expressive fixtures generator
nikic/php-parser                      v3.1.5              A PHP parser written in PHP
nyholm/psr7                           0.3.0               A fast PHP7 implementation of PSR-7
ocramius/package-versions             1.3.0               Composer plugin that provides efficient querying for installed package versions (no runtime IO)
ocramius/proxy-manager                2.1.1               A library providing utilities to generate, instantiate and generally operate with Object Proxies
omnipay/common                        v3.0.2              Common components for Omnipay payment processing library
omnipay/omnipay                       dev-master 681fd1d  Omnipay payment processing library
oneup/flysystem-bundle                dev-master 04b55a9  Integrates Flysystem filesystem abstraction library to your Symfony2 project.
paragonie/random_compat               v2.99.99            PHP 5.x polyfill for random_bytes() and random_int() from PHP 7
pda/pheanstalk                        v3.0.2              PHP client for beanstalkd queue
php-http/discovery                    1.4.0               Finds installed HTTPlug implementations and PSR-7 message factories
php-http/guzzle6-adapter              dev-master 54181ff  Guzzle 6 HTTP Adapter
php-http/httplug                      v1.1.0              HTTPlug, the HTTP client abstraction for PHP
php-http/message                      1.6.0               HTTP Message related tools
php-http/message-factory              v1.0.2              Factory interfaces for PSR-7 HTTP Message
php-http/promise                      v1.0.0              Promise used for asynchronous HTTP requests
php-imap/php-imap                     2.0.3               PHP class to access mailbox by POP3/IMAP/NNTP using IMAP extension
phpcollection/phpcollection           0.5.0               General-Purpose Collection Library for PHP
phpdocumentor/reflection-common       1.0.1               Common reflection classes used by phpdocumentor to reflect the code structure
phpdocumentor/reflection-docblock     3.3.2               With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.
phpdocumentor/type-resolver           0.4.0
phpoption/phpoption                   1.5.0               Option Type for PHP
phpseclib/phpseclib                   2.0.11              PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.
phpspec/prophecy                      1.7.6               Highly opinionated mocking framework for PHP 5.3+
phpunit/php-code-coverage             4.0.8               Library that provides collection, processing, and rendering functionality for PHP code coverage information.
phpunit/php-file-iterator             1.4.5               FilterIterator implementation that filters files based on a list of suffixes.
phpunit/php-text-template             1.2.1               Simple template engine.
phpunit/php-timer                     1.0.9               Utility class for timing
phpunit/php-token-stream              2.0.2               Wrapper around PHP's tokenizer extension.
phpunit/phpunit                       5.7.27              The PHP Unit Testing framework.
phpunit/phpunit-mock-objects          3.4.4               Mock Object library for PHPUnit
piwik/device-detector                 3.10.2              The Universal Device Detection library, that parses User Agents and detects devices (desktop, tablet, mobile, tv, cars, console, etc.), clients ...
ps/image-optimizer                    dev-master 7262075  Image optimization / compression library. This library is able to optimize png, jpg and gif files in very easy and handy way. It uses optipng, p...
psr/cache                             1.0.1               Common interface for caching libraries
psr/container                         1.0.0               Common Container Interface (PHP FIG PSR-11)
psr/http-client                       0.1.0               Common interface for HTTP clients
psr/http-message                      1.0.1               Common interface for HTTP messages
psr/link                              1.0.0               Common interfaces for HTTP links
psr/log                               1.0.2               Common interface for logging libraries
psr/simple-cache                      1.0.1               Common interfaces for simple caching
react/promise                         v2.7.0              A lightweight implementation of CommonJS Promises/A for PHP
ruflin/elastica                       5.x-dev 4b6cfe8     Elasticsearch Client
ruler/ruler                           dev-master 51e3eb6  A simple stateless production rules engine for PHP 5.3.
sebastian/code-unit-reverse-lookup    1.0.1               Looks up which function or method a line of code belongs to
sebastian/comparator                  1.2.4               Provides the functionality to compare PHP values for equality
sebastian/diff                        1.4.3               Diff implementation
sebastian/environment                 2.0.0               Provides functionality to handle HHVM/PHP environments
sebastian/exporter                    2.0.0               Provides the functionality to export PHP variables for visualization
sebastian/global-state                1.1.1               Snapshotting of global state
sebastian/object-enumerator           2.0.1               Traverses array structures and object graphs to enumerate all referenced objects
sebastian/recursion-context           2.0.0               Provides functionality to recursively process PHP variables
sebastian/resource-operations         1.0.0               Provides a list of PHP built-in functions that operate on resources
sebastian/version                     2.0.1               Library that helps with managing the version number of Git-hosted PHP projects
seld/cli-prompt                       1.0.3               Allows you to prompt for user input on the command line, and optionally hide the characters they type
seld/jsonlint                         1.7.1               JSON Linter
seld/phar-utils                       1.0.1               PHAR file format utilities, for when PHP phars you up
sensio/distribution-bundle            v5.0.22             Base bundle for Symfony Distributions
sensio/framework-extra-bundle         v3.0.29             This bundle provides a way to configure your controllers with annotations
sensiolabs/security-checker           v4.1.8              A security checker for your composer.lock
snc/redis-bundle                      2.1.x-dev 3b9d70d   A Redis bundle for Symfony
stof/doctrine-extensions-bundle       v1.3.0              Integration of the gedmo/doctrine-extensions with Symfony2
swiftmailer/swiftmailer               v6.0.2              Swiftmailer, free feature-rich PHP mailer
symfony/assetic-bundle                v2.8.2              Integrates Assetic into Symfony2
symfony/monolog-bundle                v3.3.0              Symfony MonologBundle
symfony/polyfill-apcu                 v1.8.0              Symfony polyfill backporting apcu_* functions to lower PHP versions
symfony/polyfill-ctype                v1.8.0              Symfony polyfill for ctype functions
symfony/polyfill-intl-icu             v1.8.0              Symfony polyfill for intl's ICU-related data and classes
symfony/polyfill-mbstring             v1.8.0              Symfony polyfill for the Mbstring extension
symfony/polyfill-php56                v1.8.0              Symfony polyfill backporting some PHP 5.6+ features to lower PHP versions
symfony/polyfill-php70                v1.8.0              Symfony polyfill backporting some PHP 7.0+ features to lower PHP versions
symfony/polyfill-util                 v1.8.0              Symfony utilities for portability of PHP codes
symfony/security-acl                  v3.0.1              Symfony Security Component - ACL (Access Control List)
symfony/swiftmailer-bundle            v3.2.2              Symfony SwiftmailerBundle
symfony/symfony                       v3.4.12             The Symfony PHP framework
theiconic/php-ga-measurement-protocol dev-master 26c09a4  Send data to Google Analytics from the server using PHP. This library fully implements GA measurement protocol.
twig/extensions                       v1.5.1              Common additional features for Twig that do not directly belong in core
twig/twig                             v2.4.8              Twig, the flexible, fast, and secure template language for PHP
webmozart/assert                      1.3.0               Assertions to validate method input/output with nice error messages.
webuni/commonmark-table-extension     dev-master d2cbc08  The table extension for CommonMark PHP implementation
willdurand/jsonp-callback-validator   v1.1.0              JSONP callback validator.
zendframework/zend-code               3.3.0               provides facilities to generate arbitrary code using an object oriented interface
zendframework/zend-eventmanager       3.2.1               Trigger and listen to events within a PHP application

@yellow1912
Copy link
Author

yellow1912 commented Jun 29, 2018

For more information, on my current installation, I created a bare service with nothing inside, then I try to get that service several times like this

$container->get('test')->getName();

The _constructor is called more than once, I went to the generated proxy cache file, put in my debug code:

use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;

// This file has been auto-generated by the Symfony Dependency Injection Component for internal use.
// Returns the private 'test' shared service.

if ($lazyLoad) {
    return $this->privates['test'] = $this->createProxy('Test_05acade', function () {
        return \Test_05acade::staticProxyConstructor(function (&$wrappedInstance, \ProxyManager\Proxy\LazyLoadingInterface $proxy) {
            $wrappedInstance = $this->load('getMyApp_TestService.php', false);

            $proxy->setProxyInitializer(null);

            return true;
        });
    });
}
debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
return new \MyApp\Test();

And my debug backtrace looks like this:

#0 require() called at [path/cache/dev/ContainerPvxcwug/appDevDebugProjectContainer.php:4806] 
#1 ContainerPvxcwug\appDevDebugProjectContainer->load() called at [path/cache/dev/ContainerPvxcwug/getMyApp_Control_TestService.php:11] 
#2 ContainerPvxcwug\appDevDebugProjectContainer->{closure}() 
#3 Closure->__invoke() called at [path/cache/dev/ContainerPvxcwug/Test_05acade.php:28] 
#4 Test_05acade->getName() called at [path/vendor/app/Bundle/control-bundle/Controller/Frontend/InstanceController.php:34] 
#5 MyApp\ControlBundle\Controller\Frontend\InstanceController->logAction() called at [path/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php:151]
#6 Symfony\Component\HttpKernel\HttpKernel->handleRaw() called at [path/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php:68]
#7 Symfony\Component\HttpKernel\HttpKernel->handle() called at [path/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php:200]
#8 Symfony\Component\HttpKernel\Kernel->handle() called at .....

If getName is called 5 times then the above backtrace will be printed out 5 times. For some reason the function was triggered with lazyLoad = false more than once?

(I formatted the code a bit to remove sensitive information)

@xabbuh
Copy link
Member

xabbuh commented Jun 29, 2018

You mean that the stack trace is exactly the same five times? That would be weird as I don't see why your kernel should handle five requests. I think it would still help a lot if you could create a small example application that would allow to reproduce the issue.

@yellow1912
Copy link
Author

yellow1912 commented Jun 29, 2018

I tracked it down to this single file that is causing the issue: src/Symfony/Bridge/ProxyManager/LazyProxy/PhpDumper/ProxyDumper.php

If I simply use the whole source of 3.4.12 with the ProxyDumper.php from 3.4.11 then it works. I did this simple test:

  1. Keep the whole source code intact, use symfony 3.4.12
use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;

// This file has been auto-generated by the Symfony Dependency Injection Component for internal use.
// Returns the private 'app.product.handler.product' shared service.

if ($lazyLoad) {
    return $this->privates['app.product.handler.product'] = $this->createProxy('ProductHandler_922ff44', function () {
        return \ProductHandler_922ff44::staticProxyConstructor(function (&$wrappedInstance, \ProxyManager\Proxy\LazyLoadingInterface $proxy) {
            $wrappedInstance = $this->load('getApp_Product_Handler_ProductService.php', false);

            $proxy->setProxyInitializer(null);

            return true;
        });
    });
}

return new \App\ProductBundle\Handler\ProductHandler();
  1. Keep the whole source code and symfony 3.4.12 intact, only replace src/Symfony/Bridge/ProxyManager/LazyProxy/PhpDumper/ProxyDumper.php from 3.4.11
use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;

// This file has been auto-generated by the Symfony Dependency Injection Component for internal use.
// Returns the private 'app.product.handler.product' shared service.

if ($lazyLoad) {
    return $this->services['app.product.handler.product'] = $this->createProxy('ProductHandler_922ff44', function () {
        return \ProductHandler_922ff44::staticProxyConstructor(function (&$wrappedInstance, \ProxyManager\Proxy\LazyLoadingInterface $proxy) {
            $wrappedInstance = $this->load('getApp_Product_Handler_ProductService.php', false);

            $proxy->setProxyInitializer(null);

            return true;
        });
    });
}

return new \App\ProductBundle\Handler\ProductHandler();

Now everything runs correctly. As you can see, the first scenario my service was put inside $this->privates, the second one it is put inside $this->services, there was no other change in my code or configs.

PS: I'm trying to setup a test application to re-produce the issue, but so far I haven't been able to re-produce the issue yet unless I use it on my exact dev env. I suspect the issue is with either my code or a 3rd party plugin, but I haven't been able to nail it down yet. So far I know the latest change in ProxyDumper causes the issue, probably in combination with some issue from my code.

@stof
Copy link
Member

stof commented Jun 29, 2018

@nicolas-grekas related to #27593

@nicolas-grekas
Copy link
Member

Indeed. Fixed in #27776.

nicolas-grekas added a commit that referenced this issue Jun 29, 2018
… (nicolas-grekas)

This PR was merged into the 3.4 branch.

Discussion
----------

[ProxyManagerBridge] Fix support of private services (bis)

| Q             | A
| ------------- | ---
| Branch?       | 3.4
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #27756
| License       | MIT
| Doc PR        | -

Commits
-------

3ca0c86 [ProxyManagerBridge] Fix support of private services (bis)
gggeek added a commit to kaliop-uk/ezmigrationbundle that referenced this issue Jul 16, 2018
add symfony 3.4.12 as conflicting version, because of symfony/symfony#27756, which cause bug #165
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

7 participants