Coder Social home page Coder Social logo

dii's Introduction

Dii

Dependency Injection Container Plugin for Yii 1

This plugin adds the ability to configure object instances and their dependencies before they are used, and to store them into a container class to easy access.

It uses the clean and flexible Ray.Di DI framework which is a PHP dependency injection framework in the style of "Google Guice".

Ray.Di also allows you to program using AOP, that is, decorating the configured instances so some logic can be run before or after any of their methods.

Configuration

Bootstrap file

Use composer autoloader instead of Yii autoloader.

// composer autoloader
require dirname(__DIR__) . '/vendor/autoload.php';
spl_autoload_unregister([YiiBase::class, 'autoload']);

// set context module
Dii::setContext(\YourVendor\YourProject\Context\App::class);

// run the application
Yii::createWebApplication()->run();

Binding module

Modules are classes that describe how instances and their dependencies should be constructed, they provide a natural way of grouping configurations. An example module looks like this:

<?php

namespace Koriym\Dii\Module;

use Ray\Di\AbstractModule;
use Vendor\Hello\BarInterceptor;
use Vendor\Hello\Foo;
use Vendor\Hello\FooInterface;

class AppModule extends AbstractModule
{
    protected function configure()
    {
        $this->bind(FooInterface::class)->to(Foo::class);
        $this->bindInterceptor(
            $this->matcher->any(),
            $this->matcher->startsWith('actionIndex'),
            [BarInterceptor::class]
        );
    }
}

Context

You can make the necessary bindings depending on the context. The context class specifies which module to bind in.

use Koriym\Dii\Module\AppModule;
use Koriym\Dii\ModuleProvider;
use Ray\Di\AbstractModule;

class App implements ModuleProvider
{
    public function __invoke() : AbstractModule
    {
        return new AppModule();
    }
}

In this example we have overridden the binding of AppModule with TestModule.

class Test implements ModuleProvider
{
    public function __invoke() : AbstractModule
    {
        // override AppModule with TestModule
        return new TestModule(new AppModule());
    }
}

Injecting Dependencies in Controllers

Ray.Di is able to inject instances to your controllers based on annotations:

<?php

use Koriym\Dii\Injectable;
use Ray\Di\Di\Inject;
use Vendor\Hello\FooInterface;

class SiteController extends CController implements Injectable
{
    private $foo;

    /**
     * @Inject
     */
    public function setDeps(FooInterface $foo)
    {
        $this->foo = $foo;
    }

    public function actionIndex()
    {
        echo 'Hello World' . $this->foo->get();
    }
}

As soon as the controller is created, all methods having the @Inject annotation will get instances of the hinted class passed. This works only for setter method, not constructors. Please implemet marker interface Injectable to notify Ray.Di the class injectable.

Also any class created by Yii:createComponent() method is worked as well.

Demo

cd demo
composer install
composer serve

dii's People

Contributors

koriym avatar

Stargazers

 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

dii's Issues

AppModuleが存在しないエラー

https://github.com/koriym/dii/blob/master/src/Dii.php#L49 から参照しているAppModuleがソースコード上に存在しないためエラーとなっております。

エラーメッセージ
Class Koriym\Dii\Module\AppModule does not exist

デモの方には同じネームスペースでクラスが存在しているので、こちらをsrc/配下に置く必要があると思われます。
https://github.com/koriym/dii/blob/master/demo/src/Module/AppModule.php

Use Dii in console application

Dii in console application

CConsoleCommand は CConsoleCommandRunner::createCommand でインスタンス化される。このメソッド中で CConsoleCommand を直接 new している箇所は下記の行のみです。

https://github.com/yiisoft/yii/blob/master/framework/console/CConsoleCommandRunner.php#L170

ここで Dii:createComponent によって初期化するように修正すれば、consoleアプリケーションにおいてもDiiを利用できる。

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.