Andrej
Andrej

Reputation: 425

Using Interfaces And DI In Yii Controllers

I want to work with Interfaces and Dependency Injection in my Yii 1.1.14 project. Here is the demo code that I have:

The interface:

interface IUserInterface
{   
    public function DoSomething();
}

The class:

class UserService implements IUserInterface
{
    public function DoSomething()
    {
        echo "TEST TEST";
    }
}

Now comes the part that is problematic for me. How do I inject the interface in my controller?

I have tried this:

class AccountController extends Controller
{       
    protected $userService;

    public function __construct(IUserInterface $userInterface) 
    {
        $this->userService = $userInterface;

        parent::__construct();
    }    

    public function actionTest()
    {
        $this->userService->DoSomething();
    }
}

but this won't work, because of CController constructor:

public void __construct(string $id, CWebModule $module=NULL)

What should I do, so I can use the interface in my controller?

I asked the same question on the Yii forum, but we ended up going in circles: http://www.yiiframework.com/forum/index.php/topic/52810-using-interfaces-and-di-in-yii-controllers/

Upvotes: 0

Views: 2555

Answers (2)

Matthieu Napoli
Matthieu Napoli

Reputation: 49573

This is the same problem with Zend Framework 1: the framework uses the constructor so you can't use it for dependency injection.

What I have done to integrate PHP-DI in ZF1 is I override the "Dispatcher" of the framework, that is the object which is responsible to create the controller.

By overriding it, I can control how the controller is created and thus inject dependencies.

Have a look here: https://github.com/mnapoli/PHP-DI-ZF1

Upvotes: 1

darkheir
darkheir

Reputation: 8950

It's not easy to use dependency injection in Yii since the framework hasn't been created with the idea to use it.

There is one extension letting you use dependency Injection: http://www.yiiframework.com/extension/yiipimple

I havn't tried it so I can't tell you if this extension is answering to your needs.

Upvotes: 1

Related Questions