简体   繁体   中英

Dependency Injection

I have this code

Controller

<?php

namespace App\Exchange\Helpers;

use App\Contracts\Exchange\Notification;

class Locker
{
    protected $notification;

    public function __construct(Notification $notification)
    {
        $this->notification = $notification;
    }

    public function index()
    {
        return $this->notification->sendMessage('test');
    }

Interface

<?php

namespace App\Contracts\Exchange;

interface Notification
{
    public function sendMessage($message);
}

File Kernel.php

namespace App\Providers;

use App\Contracts\Exchange\Notification;
use App\Exchange\Helpers\Notification\Telegram;
use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(Notification::class, function (){
            return new Telegram(env('TELEGRAM_EXCHANGE_TOKEN'), env('TELEGRAM_EXCHANGE_CHAT_ID'));
        });
    }

If I try to use new Locker(); I get a TypeError error: Too few arguments to function App\Exchange\Helpers\Locker::__construct(), 0 passed in Psy Shell code on line 1 and exactly 1 expected

Your controller should extend Illuminate\Routing\Controller in order for dependency injection to work. Or just refactor your __construct method using app helper:

<?php

namespace App\Exchange\Helpers;

use App\Contracts\Exchange\Notification;

class Locker
{
    protected $notification;

    public function __construct()
    {
        $this->notification = app(Notification::class);
    }

    public function index()
    {
        return $this->notification->sendMessage('test');
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM