首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >依赖注入

依赖注入
EN

Stack Overflow用户
提问于 2022-07-22 08:22:25
回答 1查看 38关注 0票数 1

我有这个密码

控制器

代码语言:javascript
复制
<?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');
    }

接口

代码语言:javascript
复制
<?php

namespace App\Contracts\Exchange;

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

文件Kernel.php

代码语言:javascript
复制
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'));
        });
    }

如果我尝试使用新的Locker();,就会得到一个TypeError错误:对于函数App\Exchange\Helpers\Locker::__construct()来说,参数太少了,0在第1行的Psy Shell代码中传递,而确切地说是1期望的

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-22 10:11:01

您的控制器应该扩展Illuminate\Routing\Controller,以便依赖注入工作。或者使用__construct助手重构您的app方法:

代码语言:javascript
复制
<?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');
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73077259

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档