Code Monkey home page Code Monkey logo

zend-di's Introduction

zend-di

Repository abandoned 2019-12-31

This repository has moved to laminas/laminas-di.

Build Status Coverage Status

zend-di provides autowiring to implement Inversion of Control (IoC) containers. IoC containers are widely used to create object instances that have all dependencies resolved and injected. Dependency Injection containers are one form of IoC โ€“ but not the only form.

zend-di is designed to be simple, fast and reusable. It provides the following features:

  • Constructor injection
  • Autowiring:
    • Recursively through all dependencies
    • With configured type preferences
    • with configured injections
    • With injections passed in the create() call
  • Code generators to create factories usable by other IoC containers like Zend\ServiceManager

It does not provide:

  • Setter, interface, property or any other injection method than constructor injection
  • Support for factories
  • Declaring shared/unshared instances
    • the injector always creates new instances
    • the default container always shares instances
  • Support for variadic arguments in __construct

If you need these features combine it with another IoC container such as zend-servicemanager.

zend-di's People

Contributors

akrabat avatar bakura10 avatar dasprid avatar evandotpro avatar ezimuel avatar freeaqingme avatar froschdesign avatar jonathanmaron avatar koopzington avatar maks3w avatar marc-mabe avatar michalbundyra avatar micheh avatar mikaelkael avatar mpinkston avatar mwillbanks avatar nickpeirson avatar noopable avatar ocramius avatar prolic avatar ralphschindler avatar samsonasik avatar sgehrig avatar socalnick avatar thinkscape avatar tux-rampage avatar vahid-sohrabloo avatar veewee avatar wdalmut avatar weierophinney 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

Watchers

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

zend-di's Issues

Improve migration from zend-servicemanager-di

From PR #35

ZF is aiming to allow easy migrations to new component versions whenever possible. For zend-di there is a component that integrated version 2 into zend-servicemanager.
Version 3 introduced a conflict-entry in it's composer.json, that states clearly zend-servicemanager-di is no longer needed. But it will also urge consumers to potentially upgrade many parts of their application.

To make life easier for these users, we should provide a new version for zend-servicemanager-di, that will deprecate it's own usage but allowing the user's to remove it's parts step by step.

Link to the discourse topic

This issue should keep track of this topic after migration to Laminas is complete.

Check All Headers In Documentation

Check headers are correct

TLDR; Headers should use the #, ## etc to format different levels of headers, and not be underlines using ===== or ``-----`, or be psuedo header using bold

Check all headers on the documentation - headers should use the hash style of declaration rather then be underlined with equals or dashes. The more hashes, the more of a subheading. Eg:

  • # is equal to <h1>
  • ## is equal to <h2>
  • ### is equal to <h3>
  • #### is equal to <h4>
  • ##### is equal to <h5>

Headings should be appropriate for their level in the documentation.

Psuedo headers using bold tags ** should be replaced with appropriate level of heading tag.

Add return types to test class methods

It seems methods of Test-Classes should have return types, this is not the case within this project.
The TODO would be to add these return types.

Missing information

  • Is there a commitment, rfc or discussion to refer to?
  • Link to the originating PR

Check Documentation For Other Things

Check docs for other problems

TLDR; Cast your eye over the documetation for any problems not covered in the other issues

Things slip through the net, so check the documentation for other problems that have been missed. Common other problems include

  • Bullet lists (should be single * then space at the start of line)
  • Inline code - should be marked by three backticks at start and finish
  • bookdown.json file is correctly formated and has the right escaping
  • Links between documentation using RST have been stripped
  • Any other RST has been removed correctly
  • Anything and everything not covered

If you end up fixing the same problem over and over, please ping Gary Hockin - we may be able to add bespoke issue for that problem, or fix in automated capacity

Documentation AoT - factories + injector decorator

I think the documentation is wrong:
https://docs.zendframework.com/zend-di/cookbook/aot-guide/#5-add-aot-to-the-service-manager

In getDependencies method of ConfigProvider we have:

            'factories' => $this->getGeneratedFactories(),
            'delegators' => [
                InjectorInterface::class => [
                    InjectorDecoratorFactory::class,
                ],
            ],

but I think one of this configuration is useless.
If we inject generated factories in factories key then we don't need to use decorator (which uses GeneratedInjector and in fact is an abstract factory - but uses only generated factories list).

But in case we have factories injected already into service manager the abstract factory for the service is not going to be called as the factory is defined. If the factory is not defined (so for example service was added later and factories were not regenerated) then normal injector is going to be used anyway (generated injector is just the proxy to origin injector in case factory is not defined).

Of course it doesn't change too much, but in case we need use injector (abstract factory) we don't need to check again on generated list, as this is not there.

Di Runtime Compiler Definition

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/6748
User: @nickpeirson
Created On: 2014-10-10T17:49:45Z
Updated At: 2015-03-10T07:03:50Z
Body
Seems that the current CompilerDefinition class has not been maintained with changes that have been introduced in the RuntimeDefinition. This results in different class definitions generated by the CompilerDefinition than those generated by the RuntimeDefinition. To resolve this I have created RuntimeCompilerDefinition which extends RuntimeDefinition and adds the functionality of CompilerDefinition. It has been designed to be used as a drop in replacement for the CompilerDefinition, and as such should be usable any where that was previously been used.


Comment

User: @Ocramius
Created On: 2014-10-10T17:58:42Z
Updated At: 2014-10-10T17:58:42Z
Body
@nickpeirson are there any tests for the newly introduced code?


Comment

User: @nickpeirson
Created On: 2014-10-10T18:03:47Z
Updated At: 2014-10-10T18:03:47Z
Body
Not currently.
Thinking about it, would you be happy replacing the current CompilerDefinition with this class? I can't see any reason not to as the current CompilerDefinition produces broken definitions in some cases. If so, I'll move it over to replacing it and update the tests for coverage of the newly introduced methods.
If there's a reason to leave it where it is in this PR, then I'll add the tests against it as it stands.


Comment

User: @weierophinney
Created On: 2015-02-19T19:57:08Z
Updated At: 2015-02-19T19:57:08Z
Body
@nickpeirson GO FOR IT!

If you can do this by 9 March 2015, we can include it in 2.4. :)


Comment

User: @nickpeirson
Created On: 2015-02-20T08:45:27Z
Updated At: 2015-02-20T08:45:27Z
Body
Done. I did have to make one tweak to maintain BC, which I'm not sure about.

In summary, there's a test to see if CompilerDefinition::hasMethodParameters() returns false when the class doesn't exist. However in RuntimeDefinition::hasMethodParameters(), which is where the implementation now comes from, throws a ReflectionException in this case. I've overridden the method in CompilerDefinition to catch the exception and return false, which maintains BC, but my preferred solution would be to change the test and be consistent with RuntimeDefinition.

Maintaining BC seemed to be the path of least resistance, but I'm happy to switch it over if there's a consensus on the small BC break.


Comment

User: @nickpeirson
Created On: 2015-02-20T08:49:35Z
Updated At: 2015-02-20T08:49:35Z
Body
Travis is showing failed, but it looks like the same failures as on develop, but shout if I missed something that I need to fix.


Check Documentation Code Blocks

Check code blocks are correct

TLDR; Check in all files that codeblocks are correct, in PSR-2 format and have PHP syntax highlighting applied.

Code blocks should be in the following format...

```php
 'ZEND-FRAMEWORK');

// No required options
$rendererOptions = array();
$renderer = Barcode::factory(
    'code39', 'image', $barcodeOptions, $rendererOptions
);

```

Note the three backticks then php in the opening fence, and the closing fence is just three backticks. It's common for the opening backticks to have no code type, or something like source.

Code should also have been automatically formatted into PSR-2 format, but sometimes these slip through the net.

Update Zend Coding Standard to v2

There are a lot of new conventions that are not covered by the current phpcs ruleset of zend-coding-standard (v1.x).

Some examples are (incomplete list):

  • Whitespace after cast operators
  • Whitespace after not operator (!)
  • Whitespaces before and after ternary operators
  • Trailing comma for the last element in array declarations

A new coding style and tooling is currently work in progress at zendframework/zend-coding-standard#5. When this PR is merged and v2 is released this zend-di should integrate it.

Depending on my availability, I'll perform the tests as suggested in the mentioned PR.

Add strict types

According to the CS/Best Practices, all PHP files should declare(strict_types=1)

Better AoT compiler

In order to improve AoT compiler, on my project I've done some changes.

The problem is that with AoT, dependency factories are not created. To accomplish my goal I've made a simple DependencyScanner that try to fetch every dependency classes:

<?php

declare(strict_types=1);

namespace AppAoT\Scanner;

use Zend\Code\Reflection\ClassReflection;

class DependencyScanner
{
    /** @var string[] */
    private $classNamesToScan;

    /** @var string[] */
    private $classNames = [];

    /** @var bool */
    private $isScanned = false;

    /**
     * DependencyScanner constructor.
     *
     * @param string[] $classNamesToScan
     */
    public function __construct(array $classNamesToScan = [])
    {
        $this->classNamesToScan = $classNamesToScan;
    }

    protected function scan(): void
    {
        if ($this->isScanned) {
            return;
        }

        foreach ($this->classNamesToScan as $className)
        {
            $this->scanClass($className);
        }

        $this->isScanned = true;
    }

    protected function scanClass(string $name): void
    {
        if (! \class_exists($name)) {
            return;
        }

        if (\array_key_exists($name, $this->classNames)) {
            return;
        }

        $this->classNames[$name] = true;

        $classReflection = new ClassReflection($name);
        $constructor = $classReflection->getConstructor();

        if (null === $constructor) {
            return;
        }

        $parameters = $constructor->getParameters();

        foreach ($parameters as $parameter) {
            $class = $parameter->getClass();

            if (null === $class) {
                continue;
            }

            $this->scanClass($class->getName());
        }
    }

    /**
     * @return string[]
     */
    public function getClassNames(): array
    {
        $this->scan();
        
        return \array_keys($this->classNames);
    }
}

And changed my di-generate-aot.sh to use it, getting every psr-4 namespace directory (does not support dir arrays yet), and using the previous class to fetch every dependency class.

<?php

namespace AppAoT;

use AppAoT\Scanner\DependencyScanner;
use Psr\Container\ContainerInterface;
use Zend\Code\Scanner\DirectoryScanner;
use Zend\Di\CodeGenerator\InjectorGenerator;
use Zend\Di\ConfigInterface;
use Zend\Di\Definition\RuntimeDefinition;
use Zend\Di\Resolver\DependencyResolver;

require __DIR__ . '/../vendor/autoload.php';

$composerFile = __DIR__ . '/../composer.json';

if (! \is_readable($composerFile)) {
    throw new \RuntimeException('Unable to find composer.json');
}

$composer = \json_decode(\file_get_contents($composerFile), true);
$directories = \array_values($composer['autoload']['psr-4'] ?? []);

/** @var ContainerInterface $container */
$container = require __DIR__ . '/../config/container.php';
$config = $container->get(ConfigInterface::class);

$resolver = new DependencyResolver(new RuntimeDefinition(), $config);
$resolver->setContainer($container);

$scanner = new DirectoryScanner($directories);

$dependencyScanner = new DependencyScanner($scanner->getClassNames());
$classNames = $dependencyScanner->getClassNames();

$generator = new InjectorGenerator($config, $resolver, __NAMESPACE__ . '\Generated');
$generator->setOutputDirectory(__DIR__ . '/../src/AppAoT/gen');
$generator->generate($classNames);

It's just an example, but I think we can include something like that in zend-code and/or here, and improve the documentation in order to provide a better AoT compiler compared to others compiled containers.

P.S. It does not resolve aliases yet.

Feature: Create service factories for AoT

Zend\Di should provide service factories for the AoT code generators, to minimize repetetive Tasks when using AoT.

The factory should utilize the config service to obtain information such as target namespace and output directory.

Code to reproduce the issue

A developer using Zend Mvc or Expressive should be able to obtain the AoT generator like this, without additional Implementations:

/** @var \Zend\ServiceManager\ServiceManager */
$generator = $serviceManager->get(\Zend\Di\GodeGenerator\InjectorGenerator::class);

Expected results

$generator should be a ready to use generator instance.

Actual results

Service manager throws an exception.

Check Documentation Tables

Check the tables in a document

TLDR; All tables should be in the format of GHFM using | and - as horizontal and vertical separators respectively

Check all tables are in the correct format. Please don't use leading and trailing | - more information on github flavoured markdown tables can be found here.

Check For Blockquotes In Docs

Check the document for bad blockquoutes

TLDR; Check blockquotes are formatted correctly using > and check headings in blockquotes are using ###

Blockquotes are donated by a single greater than character and then a space. Make sure all the blockquotes in every doc file are correctly formatted. Headings in blockquotes should use ### and not bold.

Any paragraph spacing in blockquotes should be marked using a single greater than, then a space.

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.