Giter Site home page Giter Site logo

laminas / laminas-servicemanager Goto Github PK

View Code? Open in Web Editor NEW
141.0 27.0 54.0 3.91 MB

Factory-Driven Dependency Injection Container

Home Page: https://docs.laminas.dev/laminas-servicemanager/

License: BSD 3-Clause "New" or "Revised" License

PHP 100.00%
dependency-injection psr-11

laminas-servicemanager's Introduction

laminas-servicemanager

Build Status Psalm coverage

🇷🇺 Русским гражданам

Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.

У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.

Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"

🇺🇸 To Citizens of Russia

We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.

One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.

You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"

The Service Locator design pattern is implemented by the Laminas\ServiceManager component. The Service Locator is a service/object locator, tasked with retrieving other objects.

Benchmarks

We provide scripts for benchmarking laminas-servicemanager using the PHPBench framework; these can be found in the benchmarks/ directory.

To execute the benchmarks you can run the following command:

$ vendor/bin/phpbench run --report=aggregate

laminas-servicemanager's People

Contributors

akrabat avatar bakura10 avatar boesing avatar dasprid avatar demichl68 avatar evandotpro avatar ezimuel avatar freeaqingme avatar geeh avatar gsteel avatar kokspflanze avatar kokx avatar laminas-bot avatar maks3w avatar marc-mabe avatar michalbundyra avatar mikaelkael avatar mwillbanks avatar ocramius avatar prolic avatar ralphschindler avatar renovate-bot avatar renovate[bot] avatar samsonasik avatar sgehrig avatar snapshotpl avatar thinkscape avatar veewee avatar weierophinney avatar xerkus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laminas-servicemanager's Issues

[Zend\ServiceManager] Add alternatives services proposals when service not found is thrown

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/6836
User: @blanchonvincent
Created On: 2014-11-03T14:33:39Z
Updated At: 2015-02-19T20:09:54Z
Body
This idea comes from symfony, it would be good to add some details about services that are close (about name). This point can help developer to save time during the debug.


Comment

User: @blanchonvincent
Created On: 2014-11-03T17:21:43Z
Updated At: 2014-11-03T17:21:43Z
Body
The travis fail seems pretty strange


Comment

User: @manchuck
Created On: 2014-11-03T19:57:41Z
Updated At: 2014-11-03T19:57:41Z
Body
I would want an option to disable this feature for production.


Comment

User: @blanchonvincent
Created On: 2014-11-03T20:01:19Z
Updated At: 2014-11-03T20:01:19Z
Body
@manchuck why?


Comment

User: @manchuck
Created On: 2014-11-03T20:10:51Z
Updated At: 2014-11-03T20:10:51Z
Body
If by some chance something gets released to prod with that causes this to be called, having a lev look up can cause a slowdown. If someone finds this out, it could bring the sever to a crawl doing all these look ups


Comment

User: @blanchonvincent
Created On: 2014-11-03T20:15:55Z
Updated At: 2014-11-03T20:17:24Z
Body
@manchuck I think the lev method consume less memory cpu/memory than a big sql request, so if someone want to put the mess in your server with malicious action, it's pretty easy to do that without these lines :)


Comment

User: @blanchonvincent
Created On: 2014-11-04T20:29:08Z
Updated At: 2014-11-04T20:29:08Z
Body
@manchuck After considering it, if the developers want to handle the exception from the service manager to load services from another manager as a fallback of provide a default action, it can be good to allow to deactivate this feature. I would like other reviews about this PR. Thank you for your time. 👍


Comment

User: @mpalourdio
Created On: 2014-11-04T20:33:58Z
Updated At: 2014-11-04T20:41:06Z
Body
I'm definitely +1 with this feature for a dev environment. I like this feature in symfony. I once thought about adding it into ZDT. Maybe it would better land in ZDT, as it's more a dev specific information, no ?


Comment

User: @Ocramius
Created On: 2014-11-22T08:19:34Z
Updated At: 2014-11-22T08:19:34Z
Body
I had implemented this as an abstract factory once :-) I suggest doing the same in this case ;-)


Comment

User: @Pittiplatsch
Created On: 2014-11-24T17:54:00Z
Updated At: 2014-11-24T17:54:00Z
Body
@Ocramius Nice idea. If done properly, this abstract factory can be configured for dev env's only. 👍


Comment

User: @Ocramius
Created On: 2014-12-06T01:33:11Z
Updated At: 2014-12-06T01:33:21Z
Body
I suggest looking at https://github.com/Ocramius/zf2/blob/95ad5fd6877335f8670b3635952e5bdaa696dc00/library/Zend/ServiceManager/Zf2Compat/ServiceNameNormalizerAbstractFactory.php for that.


Comment

User: @weierophinney
Created On: 2015-02-19T20:09:54Z
Updated At: 2015-02-19T20:09:54Z
Body
I'm with @Ocramius on this one; let's implement it as an abstract factory. Developers can then enable/disable at will, and it doesn't require changes to the service manager itself.



Originally posted by @GeeH at zendframework/zend-servicemanager#129

Autowiring for scalar types

Feature Request

Q A
New Feature yes
RFC no
BC Break no

Summary

We had an enormous number of handcrafted factories in past. The fact is, once you need a scalar - you're in trouble, because ReflecitionBasedAbstractFactory has nothing to offer to you.
So we came up with our own solution - AutowiringBasedFactory, and it works well so far.

The only thing we should do to wire our scalars up:

return function(array $config) {
   return [
      GetAppVersionHandler::class => [
          'lastCommitSha' => $config['lastCommitSha']->getString(),
      ],
      ...
];

That's it, just a few lines of code in autowiring.php file. And of course, you only need to provide problematic parameters, the rest will be handled for you as before.

Alongside with that we have a console command with following compilation-phase (no runtime is needed) checks:

  1. Circular references
  2. Compound/Scalar types match
  3. Overall dependencies' config correctness
  4. Overall container consistency

With all that being said, is there any chance of our PR being merged? Given that it will satisfy all the requirements.

Overwriting an invokable with a factory does not work

Bug Report

Q A
Version(s) 3.5.1

Summary

The config get's merged not as expected.
I have a vendor's config in Module.php like this:

invokables' => [
    'lmcuser_register_form_hydrator' => \Laminas\Hydrator\ClassMethodsHydrator::class,
]

I want to overide this one with a factory in my module.config.php:

    'service_manager' => [
        'factories' => [
            'lmcuser_register_form_hydrator' => DoctrineHydratorfactory::class,
        ],

Current behavior

If I try to get the 'lmcuser_register_form_hydrator' from ServiceManager I get the ClassMethodsHydrator::class.

How to reproduce

Just overwrite a invokable (which gets aliased) with a factory and try to get it with dem sm.

Expected behavior

I would expect to get an Object from the DoctrineHydratorfactory::class which would give me in my case a DoctrineObject.

I think it has to do with the way invokables get aliased and then merged with the other config.
Maybe the array_merge arguments just have to be switched?

Servicemanager.php on line 325

            if (! empty($aliases)) {
                $config['aliases'] = (isset($config['aliases']))
                    ? array_merge($config['aliases'], $aliases)
                    : $aliases;
            }

Created tool to inject factory maps into configuration

This patch adds a new tool, create-factory-map, which will map a given class to a given factory in the specified configuration file, under the provided configuration key (defaulting to service_manager).

Usage:

  ./vendor/zendframework/zend-servicemanager/bin/create-factory-map [-h|--help|help] <configFile> <className> <factoryName> [<key>]

Arguments:

  -h|--help|help    This usage message
  <configFile>      Path to an config file in which to map the factory.
                    If the file does not exist, it will be created. If
                    it does exist, it must return an array.
  <className>       Name of the class to map to a factory.
  <factoryName>     Name of the factory class to use with <className>.
  [<key>]           (Optional) The top-level configuration key under which
                    the factory map should appear; defaults to
                    "service_manager".

As part of this work, I moved the methods for dumping configuration files into a trait; this trait is now composed by both the ConfigDumper and FactoryMapperCommand.


Originally posted by @weierophinney at zendframework/zend-servicemanager#161

Bug with array_merge_recursive

I'm trying to do something like this:

$config1 = [
    'factories`=> [
        // factories
    ],
    'lazy_services' => [
        'class_map' => [
            'Foo' => 'Foo',
        ],
    ],
];
$config2 = [
    'factories`=> [
        // factories
    ],
    'lazy_services' => [
        'class_map' => [
            'Foo' => 'Foo',
        ],
    ],
];

$container = new ServiceManager($config1);
$container->configure($config2);

This will result on internal lazy_services property the following:

$this->lazy_services = [
    'class_map' => [
        'Foo' => [
            'Foo',
            'Foo',
        ],
    ].
];

The problem is the use of array_merge_recursive() function in this line.

Same problem with delegators property.

I found this issue using zend-mvc and an already configured container, then Zend\ModuleManager\Listener\ServiceListener reconfigure it adding configuration from ModuleManager features.


Originally posted by @thomasvargiu at zendframework/zend-servicemanager#279

Write new tutorial documentation for moving from ConfigAbstractFactory

It might be a good idea to demonstrate in the documentation a migration path from this abstract factory to an explicit factory. One of the frequent comments I've seen from folks about the deprecation of ServiceLocatorAware is that developers are unaware of how to write factories. Including some explicit steps here will help them when they have the question of, "I need to do something that falls outside the scope of this abstract factory, but I don't know how."


Originally posted by @GeeH at zendframework/zend-servicemanager#149

ServiceManager runs OOM on circular dependency

Bug Report

Q A
Version(s) 3.6.4

Summary

Creating a circular dependency will trigger an OOM instead of a catch.

Current behavior

The application runs OOM

How to reproduce

I do not have an exact code block but i can explain the scenario i am facing. I have an application which uses Monolog to write logs to disk. In the factory i am creating an UserProcessor which injects the current logged in user to the log. To do this the factory uses the Laminas AuthenticationService to retrieve the user.

The problem is there that this service holds an alias. In basic setup this is not wrong however the factory that handles this is dependent on another service which depends on the logger. With this approach the logger has a dependency on the logger itself while constructing and is therefor in an endless loop.

Result is an OOM

Expected behavior

Would be good if a circular dependency would be catching. Letting the app run OOM is always a bad thing

Make code more modern and implement php 7.4 type declarations

[x] add declare(strict_types=1) to all src and test files
[x] add parameter type declarations where appropriate
[x] add return type declarations where appropriate
[ ] add property types
[ ] update code style to PSR-12
[ ] Update composer dependencies including PHPUnit to modern versions
[ ] rejoice in a job well done

Conflict in doc and implementation

The documentation states that a factory stored in a class would implement FactoryInterface but it doesn't reference which one. In ZF3 there still exists the ZF2 FactoryInterface which requires a 'createService' method while the ZF3 interface requires '__invoke'.

It is confusing to still have the ZF2 implementation out there when the clear direction in the docs in ZF3. Perhaps it should be removed?


Originally posted by @robob4him at zendframework/zend-servicemanager#144

Improve Delegator Documentation Specifically for Aliased Services

RFC

Q A
Proposed Version(s) current
BC Break? No

Goal

Update docs to state that delegators cannot target service aliases.

Background

For some reason, I personally can never remember that you can't wrap a service alias with a delegator - you must target the service name that corresponds to concrete factory.

Because this frequently trips me up, I'd like to submit a pull request to update the docs at delegators.md - so I hope it's OK to leave this issue here as a reminder for myself to do this when I have time…

FWIW, I get that the point of delegators is to modify instantiation logic, but what is the primary reason that this does not apply to aliases (If anyone has the time to comment)??

LazyServiceFactory class_exists feature

Hello, in the lazy_services configuration is a class_map array.
That array looks for most of my services like this:

[
    Foo::class => Foo::class,
    Bar::class => Bar::class,
]

For one Service i need a factories entry, a delegators entry and a class_map entry to the service_manager configuration.
Is it possible to add a class_exists option as "feature" to the LazyServiceFactory?

if (isset($this->servicesMap[$name])) {
    return $this->proxyFactory->createProxy($this->servicesMap[$name], $initializer);
} elseif ($this->useClassExists && class_exists($name)) {
    return $this->proxyFactory->createProxy($name, $initializer);
}

Originally posted by @tommyseus at zendframework/zend-servicemanager#185

Version 3.11 conflicts with ext-psr

When psr extension is loaded

Fatal error: Uncaught ValueError: class_alias(): Argument #1 ($class) must be a user-defined class name, internal class name given in ......src/autoload.php:13

so class_alias cannot be used there

Cannot declare interface Interop\Container\Exception\NotFoundException, because the name is already in use

BC Break Report

Q A
Version 3.11
PHP-FPM with opcache.preload enabled 8.1.4
Symfony (with Runtime) 5.4.7

Summary

After upgrading to version 3.11 Im getting all these E_WARNING messages in my logs and monitoring tools. Im using Symfony 5.4 and FPM with opcache.preload enabled. When I disable preload the warning goes away.

E_WARNING: Cannot declare interface Interop\Container\Containerinterface, because the name is already in use
in class_alias called at /app/vendor/laminas/laminas-servicemanager/src/autoload.php (13)
in require called at /app/vendor/composer/autoload_real.php (55)
in composerRequire6635dcbc130fab9e00890c611d69ace8 called at /app/vendor/composer/autoload_real.php (38)
in ComposerAutoloaderInit6635dcbc130fab9e00890c611d69ace8::getLoader called at /app/vendor/autoload.php (12)
in require_once called at /app/vendor/autoload_runtime.php (5)
in require_once called at /app/public/index.php (9)

And also for line 14/15 I get the warning about ContainerException/NotFoundException.

By upgrading to version 3.11 the Interop package got removed. I have no other references to Interop in my generated preload files or any other place. I think its related to opcache.preload, but im not sure.

In a previous version of the src/autoload.php file, there was an class_exists check before the alias:
0732d65#diff-984b8e3111197dd008894b4b1575ffcbda5c801cb8857434cc2898b5dca67873R13

But when I use that version, the warning is still present.

Downgrading to 3.10.* resolves the issue.

Update psr/container

Feature Request

Q A
New Feature yes
RFC yes/no
BC Break yes/no

Summary

Hi, is it possible to upgrade to psr/container version 2?

syntax error unexpected '?' expecting function error PHP 7.4.23

Bug Report

Magento 2.4.3 Version
On Composer Install we require the laminas-servicemanager library.
The library has been Installed.

Q A
Version(s) 3.10.0

Summary

facing critical log as [2021-09-29 09:46:24] main.CRITICAL: ParseError: syntax error, unexpected '?', expecting function (T_FUNCTION) or const (T_CONST) in /home/production/vendor/laminas/laminas-servicemanager/src/ServiceManager.php:115

Current behavior

Critical Log after Update the library

How to reproduce

Framework: Magento
PHP: 7.4.23

Add Product to the cart
Move to the checkout page
Show the system.log there's error log reported as in describing

Expected behavior

If PHP 7.4 supports the library then no need for such an error because the environment is already working with PHP 7.4.23

Dependency issue with test requirement

This component ships a trait used by other components in tests.
Now with 07d53d3 the tests have been upgraded to PHPUnit5 and tests of other components fails because they still using PHPUnit4.
E.g.: https://travis-ci.org/marc-mabe/zend-cache/jobs/203261654

The main problem is not to have a reusable trait for tests or the upgraded PHPUnit dependency but:

  • The dependency of PHPUnit5 is defined in require-dev - so only valid running zend-servicemanager in development environment but not verified by other components
  • Can't be moved to require as then every production environment would load PHPUnit and it's dependencies
  • The test trait will be available for everyone even in production environment but they shouldn't use it 😕
  • The test trait is in namespace Zend\ServiceManager\Test but it should be in ZendTest\*

To solve this I would do the following (like what I started to do with splitting zend-cache):

  • create own repo for reusable test classes (like zend-servicemanager-test)
    • set autoload (not autoload-dev) to load the common test classes in namespace ZendTest\*
    • set require (not require-dev) to depend on zend-servicemanager and everything else required to use these test classes
  • add require-dev: zend-servicemanager-test in this component and all components using this class
    -> Now the dependencies of such test classes are defined by composer and they are not part of any production environment

How this would look like as I started to do that with zend-cache:

Ping @weierophinney @Ocramius


Originally posted by @marc-mabe at zendframework/zend-servicemanager#182

`ContainerInterface` reference was changed in a minor release

BC Break Report

Q A
Version 3.5.0

Summary

I waited for this day since two years or so, but did not expect this to happen on a minor release. Is it intentional that the Laminas\ServiceManager\Factory\FactoryInterface now uses Psr\Container\ContainerInterface instead of Interop\Container\ContainerInterface and all my factories are broken now, while I've only updated to minor version 3.5.0? Not even a single word in the changelogs. Shouldn't such a small change with huge impact be done in the 4.0 release?

Can we have an upgrade guide please?

DI-like PHP Attributes (Autowiring feature)

Feature Request

Q A
New Feature yes
RFC no
BC Break no

Summary

Hi!
We have MVP solution for autowiring (auto-generate PHP configs for service-manager): https://github.com/opsway/laminas-service-manager-attributes

It is looks like:

#[DI\Factory(InvokableFactory::class)]
#[DI\AliasTo(Example6Service::class)]
class Example1Service implements Example6Service
{
}

or even

#[DI\AutoWireFactory]
class Example4Service
{
    public function __construct(
        #[DI\InjectService(Example2Service::class)] private $example3,
        private Example7ServiceInterface $example7
    ) {
    }
}

It is solution help us decrease a lot human mistakes and misconfiguration between code and configuration for dependencies.

So my question:
Should we continue develop & maintain this package as separate solution? Or we can make separate package as part of laminas vendor packages? Or even make this solution as part of core service-manager package?
What you think about it?)

Incorrect PHP version constraint

According to documentation, 3.6 and later require PHP 7.4 or later, but the package has an inadequate version constraint:

"php": "^7.3 || ~8.0.0",

This makes the package installable with PHP 7.3 when it shouldn't. The constraint should be updated.

Psalm integration

Feature Request

Q A
QA yes

Summary

As decided during the Technical-Steering-Committee Meeting on August 3rd, 2020, Laminas wants to implement vimeo/psalm in all packages.

Implementing psalm is quite easy.

Required

  • Create a .psalm.xml.dist in the project root
  • Copy and paste the contents from this psalm.xml.dist
  • Run $ composer require vimeo/psalm
  • Run $ vendor/bin/psalm --set-baseline=psalm-baseline.xml
  • Add a composer script static-analysis with the command psalm --shepherd --stats
  • Add a new line to script: in .travis.yml: - if [[ $TEST_COVERAGE == 'true' ]]; then composer static-analysis ; fi
  • Remove phpstan from the project (phpstan.neon.dist, .travis.yml entry, composer.json require-dev and scripts)
Optional
  • Fix as many psalm errors as possible.

Catch statement in service manager should handle any exception code

Hello ;

I've a service factory like this:

/**
 * Class DatabaseServiceFactory
 * @package iMSCP\Service
 */
class DatabaseServiceFactory implements FactoryInterface
{
    /**
     * Create database service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return Database
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config = Registry::get('config');
        $imscpDbKeys = new ConfigFileHandler($config['CONF_DIR'] . '/imscp-db-keys');

        if (!isset($imscpDbKeys['KEY']) || !isset($imscpDbKeys['IV'])) {
            throw new \RuntimeException('imscp-db-keys file is corrupted.');
        }

        $db = Database::connect(
            $config['DATABASE_USER'],
            Crypt::decryptRijndaelCBC($imscpDbKeys['KEY'], $imscpDbKeys['IV'], $config['DATABASE_PASSWORD']),
            $config['DATABASE_TYPE'],
            $config['DATABASE_HOST'],
            $config['DATABASE_NAME']
        );

        $db->execute('SET NAMESS `utf8`');

        return $db;
    }
}

Here, if an error occurs, a PDOException is throw. The problem is that the underlying catch statement from the service manager don't handle PDOException code and thus, the following fatal error is raised:

Fatal error: Wrong parameters for Exception([string $exception [, long $code [, Exception $previous = NULL]]]) in /var/cache/imscp/packages/vendor/zendframework/zend-servicemanager/src/ServiceManager.php on line 950

Note: Here the wrong query SET NAMESS is intentional.


Originally posted by @nuxwin at zendframework/zend-servicemanager#41

Factories created by generate-factory-for-class have fully-qualified namespace for classes pulled from the container

@weierophinney, here is the issue, as requested.

As I was researching generate-factory-for-class today to create a tutorial on it, I noticed that while most classes referenced in the factory classes it generates were relative, with their fully qualified namespaces included via use statements, classes which were pulled from the container were not.

Here's an example of what I mean:

<?php

namespace App\ServiceManager\TableGateway;

use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
use App\ServiceManager\TableGateway\JournalTable;

class JournalTableFactory implements FactoryInterface
{
    /**
     * @param ContainerInterface $container
     * @param string $requestedName
     * @param null|array $options
     * @return JournalTable
     */
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        // Note that \Zend\Db\TableGateway\TableGateway is fully qualified
        return new JournalTable(
            $container->get(\Zend\Db\TableGateway\TableGateway::class)
        );
    }
}

I'm not sure if there's something that I've missed; but to me, for consistency's sake if nothing else, it makes sense to have classes retrieved from the container be relative as well.


Originally posted by @settermjd at zendframework/zend-servicemanager#172

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Use matchDepNames instead of matchPackageNames

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

composer
composer.json
  • php ~8.1.0 || ~8.2.0 || ~8.3.0
  • brick/varexporter ^0.3.8 || ^0.4.0
  • laminas/laminas-stdlib ^3.17
  • psr/container ^1.1 || ^2.0
  • boesing/psalm-plugin-stringf ^1.4
  • friendsofphp/proxy-manager-lts ^1
  • laminas/laminas-cli ^1.8
  • laminas/laminas-coding-standard ~2.5.0
  • laminas/laminas-container-config-test ^1.0
  • lctrs/psalm-psr-container-plugin ^1.9
  • mikey179/vfsstream ^1.6.11@alpha
  • phpbench/phpbench ^1.2.7
  • phpunit/phpunit ^10.4
  • psalm/plugin-phpunit ^0.18.4
  • symfony/console ^6.0
  • vimeo/psalm ^5.22
github-actions
.github/workflows/continuous-integration.yml
.github/workflows/docs-build.yml
.github/workflows/release-on-milestone-closed.yml

  • Check this box to trigger a request for Renovate to run again on this repository

Running composer cs-check is broken on PHP 8.0

Bug Report

Q A
Version(s) 3.6.1

Summary

When running the composer command composer cs-check, you'll be greeted with the following error message:

Fatal error: Array and string offset access syntax with curly braces is no longer supported in Laminas-servicemanager/vendor/squizlabs/php_codesniffer/CodeSniffer/CLI.php on line 453

Warmup lazy services

Hi there!

I would like to generate all proxies before app deployment (like doctrine has orm:generate-proxies). Some host services (like Heroku) require to do this during "compile" process. Sure, generate on-demain works, but there is many cases when cache is purge.


Originally posted by @snapshotpl at zendframework/zend-servicemanager#278

All but the first configured initializers are ignored

BC Break Report (or bug?)

Broken version: 3.6.0
Working version: 3.5.1
Commit: d0b38fb#diff-c88e8922673ece50d04aef21f4dc95b87bd465868eb073480467f87e626e3b0aR541 merged by 0a6c0ff

Summary

This code in the ServiceManager->resolveInitializers() method:

            if (is_callable($initializer)) {
                $this->initializers[] = $initializer;
                return;
            }

causes to stop processing initializers after the first one. There should be continue, not return.

This bug probably caused by refactoring: this lines were in separate function resolveInitializer(), where return was ok. But then code had copy-pasted into foreach loop in base function, without altering return to continue.

Previous behavior

All passed initializers are processed and used.

Current behavior

Only the first initializer are processed and used.

How to reproduce

Just add two initializers to configuration:

class Test {}

$sm = new \Laminas\ServiceManager\ServiceManager([
    'invokables' => [
        Test::class => Test::class
    ],
    'initializers' => [
        function() { echo "First\n"; },
        function() { echo "Second\n"; },
    ],
]);
$sm->get(Test::class);

Expected output:

First
Second

Actual output:

First

Detect cyclic dependency using reflection abstract factory

This is a new feature whereby cyclic dependencies are detected in a bit of an edge case. Example illustrated here: https://gist.github.com/asgrim/72f3ee4c25b901ffed58501657ea98da

I've written the test which demonstrates what I'm trying to do, but the implementation I feel is really sub-par however. My plan to implement was simply to check if $requestedName === $type (i.e. the requested service name is the same as the parameter type being used), but in practice this doesn't work because $requestedName is actually the resolved name:

https://github.com/zendframework/zend-servicemanager/blob/develop/src/ServiceManager.php#L209-L222

On L209 the alias is resolved, and on L222 doCreate is called with the $resolvedName so we never have the actual originally requested service name.

Therefore the only solution I could come up with for now was to check if the $container is a ServiceManager and reverse-engineer the service name to the original alias. Really not keen on this though, but I'm lacking on any better ideas. Feedback welcome here! 👍

It's worth adding that in real terms, this is a user error, but I just wanted to catch this situation and provide some useful feedback (instead of something unclear Maximum function nesting level of '500' reached, aborting!), so if there's not a practical way to solve this problem, it simply may not be worth the effort.


Originally posted by @asgrim at zendframework/zend-servicemanager#261

Expected ConfigAbstractFactory configuration per service manager

I find the new Config Abstract Factory very handy. That saves a lot of typing. So thanks for that 👏.

One thing that keeps bothering me however is that there seems to be only a single configuration array that determinates how services in all service manager are to be instantiated. You can mix plain services, controllers and view helpers!

IMO that:

  • Introduces some possible problems if service names are identical.
  • Disallows one to properly split the configuration per service manager. When you have a lot of services it really helps to categorize them.

Another way of tackling this would be to add the config key directly as one of the components of the service manager config. But there are obviously other options.

return [
    'factories => [],
    \Zend\ServiceManager\AbstractFactory\ConfigAbstractFactory::class => []
];

I am curious what other people think; or how they tackle this problem?


Originally posted by @roelvanduijnhoven at zendframework/zend-servicemanager#212

Zend\ServiceManager\AbstractFactory\ConfigAbstractFactory::class key in config is ignored after migration to Laminas

BC Break Report

Q A
Version latest

Summary

My project is using external modules that are placed under vendor directory. Those external modules contains services that are defined under Zend\ServiceManager\AbstractFactory\ConfigAbstractFactory::class.

After project is migrated to Laminas, service manager is ignoring the services defined under Zend\ServiceManager\AbstractFactory\ConfigAbstractFactory::class.

Change resolveParameter method to protected

Feature Request

The method:

private function resolveParameter(ReflectionParameter $parameter, ContainerInterface $container, $requestedName)

Change this method to protected would be useful for other custom factories.

Q A
New Feature yes
RFC no
BC Break no

Summary

What do you think? Are there any reason, why this method (ReflectionBasedAbstractFactory's resolveParameter) is private? It is very useful, and it would be very good if I can use it in other factories without reimplementing the whole function.
If not, I can create a pull request

Psalm type `ServiceManagerConfiguration` of `ServiceManager` is invalid

Bug Report

Q A
Version(s) 3.10.0

Summary

Psalm does not understand intersection types in this combination:

array{foo:string}&AnotherImportedArrayType

https://psalm.dev/r/272229cbfa

Maybe thats a fixable bug within psalm but I think we should also raise raise the issue here.

Current behavior

WhateverManager::__construct expects array{shared_by_default?: bool}, parent type array<string, mixed> provided

How to reproduce

class WhateverManager extends AbstractPluginManager
{}

new WhateverManager(new ServiceManager(), ['foo' => 'bar']);

Expected behavior

No psalm error when analyzing code above.

Feature: ServiceManager configuration validation

Feature Request

Q A
New Feature yes

Summary

Whenever we are working in projects with own plugin managers (like laminas-validator, etc.), we do probably ignore the configuration structure which is fetched from the container.

https://github.com/laminas/laminas-validator/blob/bdd503adc83d814a5c94e598ea0eb9fc7ca56339/src/ValidatorPluginManagerFactory.php#L49


So there will be some point in time where we have to validate the plugin managers configuration. To avoid having to do this manually, I'd prefer fetching a service from the container which is able to verify that the configuration is valid.

Such method/interface like I've created in the laminas-cache component would suffice.

https://github.com/laminas/laminas-cache/blob/130cc8db636d97b8287ff817515bb1c9ae0ef099/src/Service/StorageAdapterFactoryInterface.php#L45


WDYT? Feedback very welcome.

PHP 8.0 support

Feature Request

Q A
New Feature yes

Summary

To be prepared for the december release of PHP 8.0, this repository has some additional TODOs to be tested against the new major version.

In order to make this repository compatible, one has to follow these steps:

  • Modify composer.json to provide support for PHP 8.0 by adding the constraint ~8.0.0
  • Modify composer.json to drop support for PHP less than 7.3
  • Modify composer.json to implement phpunit 9.3 which supports PHP 7.3+
  • Modify .travis.yml to ignore platform requirements when installing composer dependencies (simply add --ignore-platform-reqs to COMPOSER_ARGS env variable)
  • Modify .travis.yml to add PHP 8.0 to the matrix (NOTE: Do not allow failures as PHP 8.0 has a feature freeze since 2020-08-04!)
  • Modify source code in case there are incompatibilities with PHP 8.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.